计算输入数字的次数,直到输入第一个对称数字

Count how many times number entered until the first symmetry number is entered

本文关键字:输入 数字 第一个 对称 计算      更新时间:2023-10-16

我编写了以下代码,但仅在第一个数字对称时才有效:

对称性就像这个数字:4554(从两端读取是相同的数字)

我的问题是为什么中断仅适用于第一个数字?当我运行它时,它就会发生。

#include <iostream>
using namespace std;
int main()
{
    int n=0, z=0, r=0, x=0, m;
    for (;;) {
        cout << "Enter number: ";
        cin >> x;
        m = x;
        while(x!=0) {
            r = x % 10;
            z = z * 10 + r;
            x = x / 10;
        }
        if(m==z)
            break;
        else
            n++;
    }
    cout << n;
    return 0;
}

Move int z=0, r=0; inside for loop。

为什么不使用这段代码来知道数字是否对称?

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
    int x;
    for (;;) {
        cout << "Enter number: ";
        cin >> x;
        m = x;
        std::stringstream str;
        str << x;
        std::string number = str.str();
        if ( number == std::string( number.rbegin(), number.rend() )
            break;
        else
            n++;
    }
    cout << n;
    return 0;
}

更简单,导致相同的结果,并且肯定更容易出错;-)

如果你这样写,推理会容易得多:

#include <iostream>
bool isPalindrome(int x)
{
    int y = x;
    int z;
    while (x) {
        z = z * 10 + x % 10;
        x /= 10;
    }
    return y == z;
}
int main()
{
    int n = 0;
    int x;
    for (;;) {
        std::cout << "Enter number: ";
        std::cin >> x;
        if (isPalindrome(x))
            break;
        else
            ++n;
    }
    std::out << "Number of non-palindromes: " << n << std::endl;
    return 0;
}

具有有意义名称的函数总是有帮助的!