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

时间:2019-11-03 12:53:47

标签: 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
        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到9的每个数字1,然后10到99的每个数字2,依此类推。我现在得到的是1 2 3 4 5 6 7 8 9 11 13 15 17 19,等等。(仅显示出不平衡的数字还在进一步发展),我将非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您没有重置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;
}