我需要确定输入的数字是否具有从右到左升序的数字。

我的代码似乎无法正常工作

这是我的代码:

int n, temp;
cout << "Please enter number: ";
cin >> n;
bool ascending = true;
temp = n%10;

while (n>0)
{
    n /= 10;
    if (temp < n % 10)
    {
        ascending = false;
    }
}

if (ascending)
{
    cout << "Number is ascending";
}
else {
    cout << "Number is not ascending";
}

最佳答案

您不会在每次迭代后更新temp的值

int n, temp;
cout << "Please enter number: ";
cin >> n;
bool ascending = true;
temp = n%10;

while (n / 10 > 0)
{
    n /= 10;
    if (temp > n % 10)
    {
        ascending = false;
        break;
    }
    temp = n % 10;
}

if (ascending)
{
    cout << "Number is ascending";
}
else {
    cout << "Number is not ascending";
}

关于c++ - 如何确定数字是否具有从右到左的升序数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41649718/

10-10 21:23