数字遍历找“1”时写出错误循环
#include<iostream>
using namespace std;
int main()
{
int n, cnt=0, s;
cin >> n;
for (int i = 1; i <= n; i++)
{
while (i)//i==0时才会跳出循环,但i==0之后立即执行i++又再次进入循环,因此无限循环无结果。
{
s = i % 10;
i /= 10;
if (s == 1) cnt++;
}
}
cout << cnt << endl;
return 0;
}
因此修改:
#include<iostream>
using namespace std;
int main()
{
int n, cnt=0, s;
cin >> n;
for (int i = 1; i <= n; i++)
{
int j = i;
while (j)
{
s = j % 10;
j /= 10;
if (s == 1) cnt++;
}
}
cout << cnt << endl;
return 0;
}
注:其中int j与int i在for的初始语句中声明的变量,其作用范围是从它定义的位置开始,一直到for所带语句的作用域结束。