繁体   English   中英

逐渐打印整数的最后一位数字?

[英]Print last digits of an integer gradually?

我正在尝试打印用户输入的整数的最后一位数字。 例如,如果用户输入 5432 我的输出是 2 32 432 5432。我已经设法使用 while 循环为此编写了代码,但是我不明白为什么我的循环没有终止,请帮我终止它?

void main()
{
    //declare variables
    int input, output, modulu = 10;
    //read input from user
    cout << "Please enter a number: ";
    cin >> input;
    int test = input % modulu;   // test checks if all the number has been printed
                                 //disect number
    while (test > 0);
    {
        output = input % modulu;
        modulu = modulu * 10;
        cout << endl << output << endl;
        test = input % modulu;
    }
}

对于任何输入 > 0, test总是 > 0

您可以使用不同的循环实现相同的效果:

int input, modulu = 1;
cout << "Please enter a number: ";
cin >> input;
do {
    modulu *= 10;
    cout << endl << (input % modulu) << endl;
} while ((input % modulu) != input);

只需测试 = 输入 / 模数; 而不是测试 = 输入 % modulu;

对于初学者来说,while 语句后面有一个分号。

while (test > 0);
               ^^^

因此,只要输入数字的最后一位不等于 0,则循环是无限的。

但是,如果您删除分号,则条件无效,因为test == 0仅在最后一位数字等于 0 的情况下。

考虑到 C++ 中的main应具有返回类型int

该程序可以如下所示

#include <iostream>

int main()
{
    while ( true )
    {
        const unsigned int Base = 10;

        std::cout << "Please enter a non-negative number (0-exit): ";

        unsigned int x;

        if ( !( std::cin >> x ) || x == 0 ) break;

        unsigned int y = x;
        unsigned int modulo = 1;

        do
        {
            modulo *= Base;

            std::cout << x % modulo << std::endl;
        } while ( y /= Base );

        std::cout << std::endl;
    }
}    

如果例如输入

123456789
0

然后输出看起来像

Please enter a non-negative number (0-exit): 123456789
9
89
789
6789
56789
456789
3456789
23456789
123456789

Please enter a non-negative number (0-exit): 0

你的第一个问题在这里:

while (test > 0);

; 终止 while 语句,代码将永远留在 while 中。 换句话说 - 下面的所有代码都不会被执行。 删除;

你的第二个问题是你处理test的方式 - 不要取模,而是除以 10。 像这样:

int main()
{
    //declare variables
    int input, output, modulu = 10;
    //read input from user
    cout << "Please enter a number: ";
    cin >> input;
    int test = input;  // <------------- Just make test equal to the input
    while (test > 0)   // <------------- The ; removed
    {
        output = input % modulu;
        modulu = modulu * 10;
        cout << endl << output << endl;
        test = test / 10;       // <----------- Divide by 10
    }

    return 0;
}

请注意,上面的代码有一些零的问题,例如1001将输出1 1 1 1001而不是1 01 001 1001

您可以通过使用string而不是int的完全不同的方法来解决这个问题

喜欢:

int main()
{
    //declare variables
    string input;

    //read input from user
    cout << "Please enter a number: ";
    cin >> input;
    cout << input << endl;
    int size = input.size();
    int tmp = size;
    while (tmp >= 0)
    {
        for (int t = tmp; t < size; t ++) cout << input[t];
        cout << endl;
        --tmp;
    }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM