Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        4年前关闭。
                                                                                            
                
        
您好,我正在尝试编写C代码,提示用户输入一个正整数,然后打印出该数字中的位数。假设用户输入一个正整数,则不需要进行错误检查。

我的问题是按“ ctrl -d”后,输出始终为:

“数字位数= 1”

如果用户键入1023,程序应打印:

“数字位数= 4”

我是C语言的新手,正试图了解一下scanf的工作方式。谢谢!

#include<stdio.h>
#include<stdlib.h>

int main(void)
{
int count = 0;
char n;
printf("Enter positive int!\n");

   while(scanf("%c",&n) != EOF);
    {
     count++;
    }

printf("# of digits = %d\n", count);
return 0;
}

最佳答案

您可以使用%d格式说明符和scanf输入一个十进制整数,然后应用以下功能:

int getNumOfDigits(int num, int base /*= 10*/)
{
    int count = 0;

    if (num < 0) {
        num = -num;
    }
    while (num > 0) {
        count++;
        num /= base;
    }
    return count;
}


它未经测试,但是一般的想法是除以十,然后使用int数字的数字位数:

printf("# of digits = %d\n", getNumOfDigits(number, 10));


请注意,您还应检查从scanf返回的值以进行错误处理(当数字格式不正确时)。例如:

if (scanf("%d", &number) != 1) {
    printf("Incorrent input for decimal number!\n");
    exit(EXIT_FAILURE);
}

关于c - 如何打印用户在C中输入的数字的位数? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32279879/

10-11 12:55
查看更多