2017-03-01 32 views
-3

此代码尝试对输入数字中的数字进行计数。如何统计数字中的数字,包括前导零?

如果输入数字是06584,则此代码的输出将为4,不包括零。我怎么能得到5作为输出(所以计数零)?

#include<stdio.h> 
void main() 
{ 
    int n,c=0,d; 
    printf("Enter no\n"); 
    scanf("%d",&n); 
    while(n!=0) 
    { 
     d=n%10; 
     c++; 
     n=n/10; 
    } 
    printf("No of digits=>%d\n",c); 
} 
+8

没有数学的解决方案是要检测前导零。您必须以字符串的形式读取用户的输入并获取字符串长度。 – Kenster

+0

你应该在你的while之前添加n的'printf',你会看到前面的0(s)已经消失 – pm100

+1

'char n [100];的scanf( “%S”,正); C = strlen的(N);'。假设输入有效,这会给你数字的个数。要验证它确实是一个使用'strtol'的数字。 – kaylum

回答

0
#include<stdio.h> 
#include <string.h> 
int main() 
{ 
    char n[101]; 
    printf("Enter no\n"); 
    scanf("%100s",n); 
    printf("No of digits=>%d\n",strlen(n)); 
} 
3

如何计算一个数位,包括前导零?

要计算输入的位数(包括前导0位数),请在数字前后记录扫描偏移量。此方法会将符号字符报告为数字,但不会计入前导空格。

使用"%n"记录到目前为止扫描的字符数。 @BLUEPIXY

#include<stdio.h> 

int main() { 
    int begin; 
    int after = 0; 
    int number; 
    printf("Enter number\n"); 
    fflush(stdout); 
    //  +--- consumes leading white-space 
    //  | +- record number of characters scanned 
    scanf(" %n%d%n", &begin, &number, &after); 
    if (after > 0) { 
    printf("No of digits: %d\n", after - begin); 
    printf("Value read : %d\n", number); 
    } else { 
    puts("Invalid input"); 
    } 
} 

输出

Enter number 
    00
No of digits: 6 
Value read : 123