#include <stdio.h>
void numDigits(int count, int number) {
while (number > 0)
{
number = number / 10;
count = count + 1;
}
printf("\nThe number of positive intergers is %d.\n", count);
}
int main()
{
int number;
int count = 0;
printf("Please enter a number: ");
scanf_s("%d", &number);
numDigits(count, number);
return 0;
}
对于大于9位数字的数字,此代码将输出'9'。如果用户输入0123456789,则该值应等于10,但此代码改为显示“ 9”。
答案 0 :(得分:3)
您正在将数字另存为int
,并且不会记录前导0
。用户输入0123456789
还是123456780
对于程序都是相同的,因为两者都存储为123456789
。相反,您应该以字符串形式读取它:
char buf[20]; // holds a maximum of 20 digits, different amounts can be specified
然后再做
scanf_s("%19s", buf); // include one less than the same length that was specified in buf's definition
您甚至不需要一个函数即可对整数进行操作并计算位数,只需为此使用strlen
:
printf("\nThe number of positive intergers is %d.\n", strlen(buf));