C++需要弄清楚为什么这个 for 循环不起作用

C++ need to figure out why this for loop doesn't work

本文关键字:for 循环 不起作用 为什么 弄清楚 C++      更新时间:2023-10-16

我需要找到从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;
}