如何使用C语言编写程序统计N位数中的数字?

如题所述

算法分析:

1. 定义N 及用来统计的cnt, 用来循环的n;

2. 输入N ;

3. 将n从1到N循环, 对于每个n执行如下操作:

a) 循环取出n的每位数字值

b)判断该位是否为1, 如是则累加到cnt上。 

4. 输出结果。 

代码如下:

#include <stdio.h>
int main()
{
int n, N, cnt = 0;
scanf("%d",&N);//输入N值。
for(n = 1;n<=N; n ++)//循环执行
{
int t = n;
while(t)//循环取出每一位。
{
if(t%10 == 1) cnt++;
t/=10;
}
}
printf("%d\n", cnt);//输出结果
return 0;
}
温馨提示:答案为网友推荐,仅供参考
相似回答