1

私はプログラミング練習のウェブサイトの問題に取り組んでいます.私はすでにルビーでこれを解決し、正しい値を簡単に返しました.問題は、3桁の数字の乗算から得られる最大の回文数を見つけることです.私のコードは次のように

#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値が 1 つ高すぎて、インクリメントfの回数が多すぎます。

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