1

我一直在为一个编程实践网站解决一个问题,我已经用 ruby​​ 解决了这个问题并且很容易返回正确的值,问题是找到可以从三位数字相乘中产生的最大回文数,我的代码是如下

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int h = 0;                                      //this will hold the largest palindrome
    for (int a = 101; a < 1000; a++)                //will cycle through all three digit numbers
    {
        for (int b = 101; b < 1000; b++)            //will cycle through all three digit numbers
        {
            if (a*b%10 != 0)                        //checks to make sure last digit is not zero
            {
                int c = a*b;                        //temporary int to hold value when it is read into an array
                int d[8] = {0};                     //array to hold individual place values
                int e = 0;                          //length of number
                int f = 0;                          //will be used to trace through array
                bool g = true;                      //bool to decide whether or not a number is a palindrome
                while (c > 0)                       //until all digits have been read
                {
                    d[e] = c%10;                    //reads last digit
                    c/=10;                          //chops off last digit
                    e++;                            //grows by on for every exponent of ten
                }
                for (e; e >= f; f++)
                    if (d[f] != d[e-f])             //compares array symetrically
                        g = false;                  //if a difference is found the bool is set to false
                if (g==true)
                    h = a*b;                        //if g remains true then a new value is saved to h.
            }
        }
    }
    cout << h;
    return 0;
}

我已经对其进行了评论以使其更易于阅读,从我的错误检查中我几乎绝对肯定地确定问题出在这些行中

     for (e; e >= f; f++)
                if (d[f] != d[e-f])             //compares array symetrically
                    g = false;                  //if a difference is found the bool is set to false

不知何故,我的回文测试无法正常工作,该程序返回的值是 0,应该是 906609

4

2 回答 2

5

e开始的值太高,你增加f了太多次。

            for (e--; e >= f; f++)
            {
                if (d[f] != d[e-f])
                    g = false;
            }
于 2013-05-07T20:12:54.120 回答
3

您将 f 递增两次-一次在 for 循环中,一次在块语句的末尾。去掉f++;你声明中的最后一个。

于 2013-05-07T20:07:43.897 回答