项目Euler Palindrome#4 with C

时间:2017-08-22 21:22:48

标签: c palindrome

我发现很少有关于使用C的问题的帖子。我的代码中的大多数元素都是自己工作但是开头的迭代由于某种原因导致了问题。首先,我得到一个“退出非零状态”错误消息。当我运行a和b的较小范围的程序时,我没有收到该消息。我猜测我创建的rev_array和for_array变量存在问题。我确定我正在做一些非常愚蠢的事情,所以我提前为此道歉。

但是当我使用a和b的较小范围(例如10到25)时,程序仍然显示所有两位数字(甚至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;
}

1 个答案:

答案 0 :(得分:0)

评论中提供的答案:

每次都需要将m重置为零。 - 约翰尼·莫普

您也不需要计算长度,因为m应该包含while循环后的长度(但是您需要在顶部将其重置为0)。并且所有这些变量都应该是局部的,并且它们中的大多数(如m,n,prod)应该在内部循环内定义,范围有限。 max是唯一需要在迭代之间保留的。 - Groo