#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‘。
发布于 2018-11-29 20:36:19
您将数字保存为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));https://stackoverflow.com/questions/53539161
复制相似问题