C++ C++;需要弄清楚为什么这个for循环不';行不通
我需要找到从1到40的每个数字的位数。看起来使用for和while循环应该很简单,但我无法让它工作 我曾尝试使用“cin>>a;”,从键盘输入“a”的值,while循环对我输入的任何数字都非常有效,但当我尝试使用for循环时,它不起作用,因此问题一定存在C++ C++;需要弄清楚为什么这个for循环不';行不通,c++,for-loop,C++,For Loop,我需要找到从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 i
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;
}
intmain()
{
int a;//最初找到的数字
int digits=0;//数字“a”的位数
int temp;//临时编号“a”
对于(a=1;a您没有重置数字
值。您应该在每次迭代开始时添加行数字=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;
}
intmain()
{
int a;//最初找到的数字
int digits=0;//数字“a”的位数
int temp;//临时编号“a”
对于(a=1;非常感谢你,它很有效。我知道我错过了这么简单的东西。非常感谢!没问题。很高兴为你提供帮助如果你将数字计数部分抽象为一个函数,你就不会遇到这个错误了。函数非常重要。你在增加数字(数字+
)。为什么?