gpt4 book ai didi

c - 如何在函数中打印出大于9?

转载 作者:太空宇宙 更新时间:2023-11-04 06:49:26 25 4
gpt4 key购买 nike

#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”。

最佳答案

您将数字保存为 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));

关于c - 如何在函数中打印出大于9?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53539161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com