【问题标题】:Printing all narcisistic numbers at one digit which given by the user以用户给出的一位数打印所有自恋数字
【发布时间】:2018-08-13 15:07:48
【问题描述】:

我尝试将用户输入的位数的所有自恋数字打印出来。

例如对于输入3,程序应打印:153, 370, 371, 407。现在由于某种原因,它没有打印数字,而是什么都不打印,程序就卡住了。

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

int main() {
    int digit, a, c = 0;
    unsigned long long int count, b, sum;
    printf("Enter digits to check narcisistic: ");
    scanf("%d", &digit);
    count = pow(10, digit - 1);
    if (digit > 2) {
        while (count < pow(10, digit)) {
            b = count;
            sum = 0;
            while (count >= 1) {
                a = b % 10;
                b /= 10;
                sum += pow(a, digit);
            }
            if (sum == count) {
                printf("\n Narcissistic found:\t%llu", count);
                c++;
            }
            count++;
        }
        if (c == 0)
            printf("No Narcissistic number for this digit.");
    }
    return 0;
}

这段代码有什么问题?

【问题讨论】:

    标签: c while-loop nested-loops


    【解决方案1】:
      while(count>=1){
          a=b%10;
          b/=10;
          sum+=pow(a,digit);
      }
    

    count 在这个循环中永远不会改变,所以它将永远循环。

    【讨论】:

      【解决方案2】:

      根据@dcp 的回答。 内部的 while 循环永远不会退出。你应该循环的是位数。例如(在之前将 digNum 声明为 int 之后):

          for(digNum = digit; digNum > 0; digNum--)
          {
              a = b%10;
              b /= 10;
              sum+=pow(a,digit);
          }
      

      【讨论】:

      • 是的,但是使用 for 循环和具有有意义名称的变量会使代码的意图更加明显。干净的可维护代码是不会再次困扰您的代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 1970-01-01
      • 2012-09-09
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多