2017-08-22 6 views
-1

私はこの問題に関して、Cを使っていくつかの記事を見つけました。私のコードの要素のほとんどは、独自に動作しますが、最初は反復が何らかの理由で問題を引き起こしています。まず、「ゼロ以外のステータスで終了」というエラーメッセージが表示されます。 aとbの範囲が狭いプログラムを実行すると、そのメッセージが表示されません。私は、私が作成したrev_arrayおよびfor_array変数に問題があると推測しています。私は本当にここで何かをやっていると確信しているので、事前に謝罪します。プロジェクトオイラーPalindrome#4 with C

しかし、10と25のようにaとbの範囲を狭くすると、プログラムでは2桁の数字(11,22,33,44など)がすべて同じ順方向と逆方向でないことが表示されます。私はこれをチェックするためにprintfを使いました。

私は、ある範囲の値を反復するのではなく、aとbの固定値を使った同様のプログラムを作りました。しかし、私はなぜこれが動作していないのか理解できませんでした。コメントで提供さ

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 

int max; 
int a; 
int b; 
int prod; 
int m = 0; 
int rev_array[10000]; 
int for_array[10000]; 
int c; 
int d; 
int same = 0; 

int main(void) 
{ 
    // iterate over all 3 digit numbers in lines 19-21 
    for(a = 10; a <= 25; a++) 
    { 
    for(b = 10; b <= 25; b++) 
    { 
     max = 0; 
     prod = a * b; 
     /* thanks to Zach Scrivena for the following formula converting an integer to an array of integers posted on stackoverflow on February 5, 2009 under the subject "convert an integer number into an array" 
     */ 
     int n = prod; 
     while(n != 0) 
     { 
     rev_array[m] = n % 10; 
     n /= 10; 
     m++; 
     } 
     /* thanks to Jordan Lewis for the following int length formula posted to stackoverflow on June 18, 2010 in response to "Finding the length of an integer in C" 
     */ 
     int length = floor(log10(abs(prod))) + 1; 
     // create the forward array of the ints in prod 
     for(c = length - 1, d = 0; c >= 0; c--, d++) 
     { 
     for_array[d] = rev_array[c]; 
     } 
     // compare the forward and reverse arrays to see if they match exactly 
     for(int e = 0; e < length; e++) 
     { 
     if(for_array[e] != rev_array[e]) 
     { 
      // if they don't match then set same equal to 1 for following step 
      same = 1; 
     } 
     } 
     /* if prod is greater than max and the forward and reverse arrays are identical, then replace max with prod 
     */ 
     if(prod > max && same == 0) 
     { 
     max = prod; 
     } 
     // reset same and repeat the process 
     same = 0; 
    } 
    } 
    // print the final, greatest number that fits the preceding criteria 
    printf("new max: %i \n", max); 
    return 0; 
} 
+0

毎回「m」をゼロにリセットする必要があります。 –

+2

プロジェクトオイラーの問題#4は、最初の3つの "ベビーステップ"の後のエントリレベルの質問です。これらのサイトのアイデアは、あなた自身でそれを解決することです。そのため、彼らは「チャレンジサイト」と呼ばれています。彼らは個人的な課題です。 –

+0

'length'を計算する必要もありません。' m'は 'while'ループの後ろの長さを含んでいるはずです(ただし、最初は' 0'にリセットする必要があります)。これらの変数はすべてローカル変数でなければならず、( 'm'、' n'、 'prod'のような)ほとんどの変数は内部ループの内部で定義されるべきです。 'max'は反復の間に保存する必要がある唯一のものです。 – Groo

答えて

0

回答:

あなたがそれぞれの時間をゼロにMをリセットする必要があります。 - Johnny Mopp

また、whileループ後の長さをmに含める必要があるので(長さを計算する必要はありませんが、最初は0にリセットする必要があります)。これらの変数はすべてローカル変数でなければならず、m、n、prodのような変数のほとんどは、スコープが限定された内側ループの内部に定義する必要があります。 maxは、反復の間に保存する必要がある唯一のものです。 - Groo

関連する問題