C++需要弄清楚为什么这个 for 循环不起作用
C++ need to figure out why this for loop doesn't work
我需要找到从1到40的每个数字的位数。看起来使用for和while循环应该很简单,但我无法使其工作。
我曾尝试过用"cin>>a;"来实现这一点,从键盘输入"a"的值,while循环对我输入的任何数字都非常有效,但当我尝试用for循环来实现时,它不起作用,所以问题一定存在。
int main()
{
int a; //initially found number
int digits=0; //number of digits number "a" has
int temp; // temporary number "a"
for(a=1;a<=40;a++) // takes a number, starting from 1
{
temp=a;
while(temp!=0) //finds number of digits the number "a" has
{
temp=temp/10;
digits++;
}
cout<<digits<<endl; //prints number of digits each found number "a" has
}
return 0;
}
我应该得到的是:1代表从1到9的每个数字,然后2代表从10到99的每个数字等等。我现在得到的是1 2 3 4 5 6 7 8 9 11 13 15 17 19等等(只显示不均匀的数字(我真的很感激任何帮助。
您没有重置digits
值。您应该在每次迭代开始时添加行digits = 0
。
int main()
{
int a; //initially found number
int digits=0; //number of digits number "a" has
int temp; // temporary number "a"
for(a=1;a<=40;a++) // takes a number, starting from 1
{
digits=0;
temp=a;
while(temp!=0) //finds number of digits the number "a" has
{
temp=temp/10;
digits++;
}
cout<<digits<<endl; //prints number of digits each found number "a" has
}
return 0;
}
相关文章:
- 如何在C++中从两个单独的for循环中添加两个数组
- 为什么我的for循环不能正确获取argv
- 在基于范围的for循环中使用结构化绑定声明
- 通过for循环使用用户输入填充列表
- 使用for循环检查数组中的重复项
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 正在使用for循环创建QScatterSerie
- Python中的for循环与C++有何不同
- 在更改for循环的第三部分后,未使用for循环结果
- 在 for 循环中查找问题时遇到困难
- 嵌套for循环C++的问题(初学者)
- 如何用for循环在c++中生成单词三角形
- 如何在for循环中包含两个索引值的测试条件
- 带有多个独立参数的C++For循环
- 为什么我的程序在for循环中k=0时返回垃圾值
- 如何通过替换顺序代码的while循环来添加OpenMP for循环
- C++-For循环未执行
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- C++ 无法在字符数组中使用 for 循环打印字母模式