题目:编写一个程序,计算在区间1到n的所有整数中,数字x(0<=x<=9)共出现了多少次?
注意:11就为1出现了2次
输入第一个数为n 第二个数为x
在1到11中,即在1,2,3,4,5,6,7,8,9,10,11中数字1出现了4次
例子:
输入 11 1
输出 4
第一次错误源码:
#includeint main(void) { int n,x,a=10,b,j=0;//x大小0到9 scanf("%d",&n); scanf("%d",&x); int i; for(i=1;i<=n;i++) { while(i!=0) { b=i%10;//取出个位数 if(b==x) { j++; } i=i/10; } } printf("%d",j); }
改正后的源码(找个中间变量记录,while中的i与for中的i冲突,i的值改变,改循坏的次数达到不了)
#includeint main(void) { int n, x, a = 10, b, j = 0; //x大小0到9 scanf("%d", &n); scanf("%d", &x); int i; int temp; for (i = 1; i <= n; i++) { temp=i;//这个i在for中还是要用的,如果直接是i放到while中去的话,i的值就改变了 while (temp != 0) { b = temp % 10; //取出个位数 if (b == x) { j++; } temp = temp / 10; } } printf("%d", j); }
加油!
5.17



