如何使这个循环适用于我的回文测试?

时间:2016-02-11 16:28:35

标签: c loops palindrome

我对编码非常陌生,我需要创建一个回文测试,测试数字达到给定的限制。我理解测试数字是否是回文的算法。但是我在循环代码时遇到了问题。 输出应如下所示: 如果限制是1000:

  1. 限制| #indindromes |倒数之和
  2. 100 18 3.086147(限制的1/10)
  3. 200 28 3.157490(限制的2/10)
  4. 一直到用户提供的限制。

    我已经启动了代码但是我的代码无限循环。你能告诉我我做错了什么吗?这是我的代码。

    #include <stdio.h>
    #include <math.h>
    
    int main(void) {
        double num;
        int upperLimit = 0; //Limit of the program.
        int numPalindromes = 0;
        double sum = 0;
        int tempLim;
        int i = 1;
    
        printf("Enter the limit of the program:");  //Asks for the limit you want the program to go to
        scanf("%d", &upperLimit);
    
        // We now need to use an algorithm to test whether or not the number is a palindrome.
        while(num <= upperLimit) {
            int temp;
            int rev = 0;
            temp = num;
    
            while(temp != 0 ){
                rev = rev * 10;
                rev = rev + temp%10; // we need to add the remainder when the number is divided by 10 to the reverse.
                temp = temp/10;
            }
            /*A number is a palindrome if its reverse is equal to itself. Now we must add its reciprocal to the sum and increase the amount of palindromes by 1 if the number is a palindrome */
            if(num == rev) {
                sum = sum + (1/num);
                numPalindromes = numPalindromes + 1;
            }
    
            while (num <= upperLimit) {
                tempLim = upperLimit * (i/10);
                if (num == tempLim) {
                    printf(" %d %d %lf\n", tempLim, numPalindromes, sum);
                }
                i++;
            }
            num++;
        }
    }
    

2 个答案:

答案 0 :(得分:1)

你有这样一个片段:

while (num <= upperLimit) {
    tempLim = upperLimit * (i/10);
    if (num == tempLim) {
        printf(" %d %d %lf\n", tempLim, numPalindromes, sum);
    }
    i++;
}

但是,在循环内部都没有修改numupperLimit。因此它永远循环。

答案 1 :(得分:1)

 while (num <= upperLimit) {
        tempLim = upperLimit * (i/10);
        if (num == tempLim) {
            printf(" %d %d %lf\n", tempLim, numPalindromes, sum);
        }
        i++;
    }

num没有变化,上限没有变化。所以它无限运行。