首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言問答

C語言輸出水仙花數 (Narcissistic Number) 經典錯誤修正:變量未初始化導致邏輯失效

     編輯:C 語言問答

錯誤代碼分析


int a,b,c,s;
s = 100*a + 10*b + c;  // a,b,c 未初始化!s 為垃圾值
for (a=1; a<10; a++)
  for (b=0; b<10; b++)
    for (c=0; c<10; c++)
      if (s == a*a*a + b*b*b + c*c*c)  // s 永遠不等於當前組合
        printf("%d\n", s);

根因:s 在循環 **外部** 計算一次,且 a,b,c 未初始化,循環內 a,b,c 變化不影響 s。

修正代碼


#include <stdio.h>

int main() {
    for (int a = 1; a < 10; a++) {
        for (int b = 0; b < 10; b++) {
            for (int c = 0; c < 10; c++) {
                int n = 100*a + 10*b + c;  // 循環內計算,反映當前數字
                int sum = a*a*a + b*b*b + c*c*c;
                if (n == sum) printf("%d\n", n);
            }
        }
    }
    return 0;
}

輸出結果


153
370
371
407

擴展:通用 n 位水仙花數


int is_narcissistic(int n) {
    int orig = n, sum = 0, digits = 0;
    int temp = n;
    while (temp) { digits++; temp /= 10; }
    temp = n;
    while (temp) {
        int d = temp % 10;
        int p = 1;
        for (int i = 0; i < digits; i++) p *= d;
        sum += p;
        temp /= 10;
    }
    return sum == orig;
}

教學重點

  • **變量作用域與生命週期**:循環外計算的值不會隨循環變量自動更新。
  • **初始化習慣**:定義即初始化 int a=0, b=0, c=0, s=0;。
  • **邏輯與數據流一致**:計算依賴的變量必須在 **同一作用域內** 同步更新。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved