簡體   English   中英

無法在 C 中分配值並增加 int

[英]Unable to assign value and increment an int in C

我有這個程序可以生成給定范圍內的阿姆斯壯數字。 但問題是范圍變量(在本例中為 n)在某種程度上就像一個 const。 我不能分配一個值也不能增加它......在使用 gcc 編譯期間出現錯誤。 電源 function 工作正常(與 pow() 在 math.h 中定義的問題相同)。 我想知道為什么此代碼會發生這種情況以及可能的修復。 謝謝

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

int power(int a, int b) {
    int c = 1;
    for(int i = 0; i < b; i++) {
        c *= a;
    }
    return c;
}

void main(void) {
    int sum, y, temp;
    printf("temp, y, sum, n\n");
    for(int n = 1; n < 100; n++) {
        temp = n;
        printf("%d ", temp);
        y = 0; // y to hold the number of digits of n
        while (n > 0) {
            n = n / 10;
            y++;
        }
        printf("%d ", y);

        n = temp;
        sum = 0;

        while(n > 0) {
            sum += power((n % 10), y);
            n = n / 10;
        }

        if (temp == sum) {
            printf("%d ", sum);
        }

        printf("%d\n", n);
    }
}

Output:

temp, y, sum, n
1 1 1 0
1 1 1 0
1 1 1 0
1 1 1 0
1 1 1 0
1 1 1 0
1 1 1 0
.
.
.

你不是經常將 n 除以 10 嗎?

由於 n 是一個 integer,它以 1 開頭,而不是浮點數,它會一直設置為 0。

您的第二個while(n > 0)循環在外部for循環中有效地設置了n=0 你想使用第二個n = temp嗎?

在最后一個 printf 語句之前添加: n = temp;
試試你這樣的代碼:

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

int power(int a, int b) {
    int c = 1;
    for(int i = 0; i < b; i++) {
        c *= a;
    }
    return c;
}

void main(void) {
    int sum, y, temp;
    printf("temp, y, sum, n\n");
    for(int n = 1; n < 100; n++) {
        temp = n;
        printf("%d ", temp);
        y = 0; // y to hold the number of digits of n
        while (n > 0) {
            n = n / 10;
            y++;
        }
        printf("%d ", y);

        n = temp;
        sum = 0;

        while(n > 0) {
            sum += power((n % 10), y);
            n = n / 10;
        }

        if (temp == sum) {
            printf("%d ", sum);
        }
        n = temp;
        printf("%d\n", n);
    }
}

這是因為 n 的值在循環外設置為 0。 試試下面的代碼。

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

int power(int a, int b) {
    int c = 1;
    for(int i = 0; i < b; i++) {
        c *= a;
    }
    return c;
}

void main(void) {
    int sum, y, temp;
    printf("temp, y, sum, n\n");
    for(int n = 1; n < 100; n++) {
        temp = n;
        printf("%d ", temp);
        y = 0; // y to hold the number of digits of n
        while (n > 0) {
            n = n / 10;
            y++;
        }
        printf("%d ", y);

        n = temp;
        sum = 0;

        while(n > 0) {
            sum += power((n % 10), y);
            n = n / 10;
        }

        if (temp == sum) {
            printf("%d ", sum);
        }
        n = temp;
        printf("%d\n", n);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM