新手求问一个循环的问题

牙ww 2018-06-15 04:46:26
#include<iostream>
using namespace std;
int main()
{
int n, cnt=0, s;
cin >> n;
for (int i = 1; i <= n; i++)
{
while (i)
{
s = i % 10;
i /= 10;
if (s == 1) cnt++;
}

}
cout << cnt << endl;
return 0;
}
这样的循环嵌套是输出不了结果的,想知道原因
...全文
809 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_42477962 2018-06-18
  • 打赏
  • 举报
回复
while循环语句只有条件为0时才会跳出循环,也就是说你那个循环条件(i)永远都是非0的值,所以想要跳出循环你可以改成 i != n+1。
赵4老师 2018-06-18
  • 打赏
  • 举报
回复
学会单步调试才是根本。
Tw!light 2018-06-16
  • 打赏
  • 举报
回复
#include<iostream> using namespace std; int main() { int n, cnt=0, s; cin >> n; for (int i = 1; i <= n; i++) { while (i) { s = i % 10; i /= 10; //===> 每次i = 0 时,才退出while循环。所以退出去 i++ 又等于 1,再次进入while循环 ,所以这样无限循环下去,所以你没有输出 if (s == 1) cnt++; } } cout << cnt << endl; return 0; } 所以修改如下: 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; }
yankkk0 2018-06-15
  • 打赏
  • 举报
回复
#include<iostream> using namespace std; int main() { int n, cnt = 0, s; cin >> n; for (int i = 1; i <= n; i++) { while (i) { s = i % 10; i /= 10; if (s == 1) cnt++; cout << cnt << endl; } } //cout << cnt << endl; system("paues"); return 0; }

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧