嵌套while循环不在C中工作

时间:2016-05-21 16:22:11

标签: c while-loop

我试图通过项目euler的第四个问题取得成功:通过将2个3位数字相乘,你可以做出的最大回文数是多少?https://projecteuler.net/problem=4

我有以下代码,但它无效。出于某种原因,似乎嵌套的while循环被破坏了。它只打印数字10000到99900,这意味着嵌套的while循环只执行一次......

#include <stdio.h>
#include <string.h>


int is_a_palindrome(int test_number);

int main (void)
{
    long     result;
    long     number_x_1;
    long     number_x_2;
    long    biggest_pal;

    number_x_1 = 100;
    number_x_2 = 100;

    while (number_x_1 < 1000)
    {
        while (number_x_2 < 1000)
        {
            result = number_x_1 * number_x_2;
            printf("%li\n", result);
            if (is_a_palindrome(result) == 1)
            {
                biggest_pal = result;
                printf("palindrome found : %li", biggest_pal);
            }
            number_x_2++;
        }
    number_x_1++;
    }
    return (biggest_pal);
}

int is_a_palindrome(int test_number)
{
    int test_number_unchanged;
    int reverse;

    reverse = 0;
    test_number_unchanged = test_number;

   while (test_number != 0)
    {
      reverse = reverse * 10;
      reverse = reverse + test_number % 10;
      test_number = test_number / 10;
    }

    if (test_number_unchanged == reverse)
    {
        return (1);
    }
    else
    {
        return (0);
    }
}

3 个答案:

答案 0 :(得分:0)

你没有在外部循环中将number_x_2设置为100 ...你只在所有循环之外执行一次!

因此,当number_x_1上的第二个循环开始时,number_x_2已经处于最大值,并且内部循环(update)没有开始。

答案 1 :(得分:0)

  

检查那个简单的错误..你必须在外循环中初始化number_x_2 = 100 ..

#include <stdio.h>
#include <string.h>


 int is_a_palindrome(int test_number);

int main (void)  
{
   long     result;
   long     number_x_1;
   long     number_x_2;
   long    biggest_pal;

  number_x_1 = 100;

  while (number_x_1 < 1000)
  {
        number_x_2 = 100;
        while (number_x_2 < 1000)
        {
           result = number_x_1 * number_x_2;
           printf("%li\n", result);
           if (is_a_palindrome(result) == 1)
           {
               biggest_pal = result;
               printf("palindrome found : %li", biggest_pal);
           }
        number_x_2++;
        }
    number_x_1++;
  }
return (biggest_pal);
}

int is_a_palindrome(int test_number)
{
  int test_number_unchanged;
  int reverse;

  reverse = 0;
  test_number_unchanged = test_number;

  while (test_number != 0)
  {
    reverse = reverse * 10;
    reverse = reverse + test_number % 10;
    test_number = test_number / 10;
  }

  if (test_number_unchanged == reverse)
  {
      return (1);
  }
  else
  {
      return (0);
  }
}

答案 2 :(得分:0)

内部while循环将number_x_2发送到1000,但随后它保持为1000,因此程序在第一个循环后永远不会运行内部循环。然后程序递增number_x_1直到达到1000,程序结束。

要解决此问题,请将语句number_x_2 = 100;移至while(number_x_2 < 1000)之前的行。