为简单项目返回错误的值

时间:2013-05-07 20:02:37

标签: c++

我一直在为编程实践网站解决一个问题,我已经在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

2 个答案:

答案 0 :(得分:5)

e从一个值开始过高,并且您将f递增太多次。

            for (e--; e >= f; f++)
            {
                if (d[f] != d[e-f])
                    g = false;
            }

答案 1 :(得分:3)

你的递增f两次 - 一次在for循环中,一次在你的block语句结束时。摆脱陈述中的最后f++;