例如:如果用户输入是11234517并且想要在此输入中看到1的数字,则输出将是“1的数字是3.我希望您理解我的意思。
我只能计算整数中的位数。
#include int main() { int n, count = 0; printf("Enter an integer number:"); scanf("%d",&n); while (n != 0) { n/=10; count++; } printf("Digits in your number: %d",count); return 0; }
也许arrays是解决方案。 任何帮助,将不胜感激。 谢谢!
因此,您已经发现可以使用number / 10
将1234
转换为123
(即删除最低有效数字)。
如果我们想获得最低有效数字,我们可以使用number % 10
。 对于1234
,其值为4
。
了解这一点,我们可以修改您的代码以考虑到这一点:
int main() { int n, count = 0; printf("Enter an integer number:"); scanf("%d",&n); while (n != 0) { if (n % 10 == 1) count++; n /= 10; } printf("Number of 1s in your number: %d", count); return 0; }
你不需要数组。 尝试这样的事情:
int countDigits(int number, int digitToCount) { // Store how many times given number occured int counter = 0; while(number != 0) { int tempDigit = number % 10; if(tempDigit == digitToCount) counter++; number = number/10; } return counter; }
您可能希望将int转换为如下字符串 :
char str[100]; sprintf(str, "%d", n);
然后,您可以迭代str
以查找数字的出现次数。
以上就是c/c++开发分享C中的整数中的特定数字计数相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/541672.html