簡體   English   中英

沒有printf,For循環不起作用

[英]For Loop Doesn't Work Without printf

我有兩個問題。

我想編寫一個解決方程的函數:

int equation() {
    int n, r, s;

    printf("\nEnter the value of N: ");
    scanf("%d", &n);

    printf("Enter the value of R: ");
    scanf("%d", &r);

    printf("Enter the value of S: ");
    scanf("%d", &s);

    int i, j, k;
    int c = 0;
    int a[r], b[s];

    a[0] = 1;
    for (i = 1; i <= r; i++) {
        a[i] = a[i-1] * ((((i * i * i) * 3) + 5) / (i * i));
    }

    for (j = 1; j <= s; j++) {
        b[j] = b[j-1] + sqrt(3 * (j * j * j) + j + 2) / (2 * j);
    }
    // The last for loop
    for (k = 1; k <= n; k++) {
        c += a[k] / b[k];
    }

    printf("Result: %d \n \n", c);

    return c;
}

如果最后一個for循環中包含以下行,則效果很好:

printf("%d, %d, %d", c, a[k], b[k]);

但是,如果最后一個沒有上面的行,則返回0 可能是什么問題?

期望值:

n,r,s = 1結果應為8。

n,r,s = 2結果應為36。

n,r,s = 3結果應為204。

如果將printf行寫入最后一個,則得到這些值。

我也想問另一個問題。 當我改變這行

a[i] = a[i-1] * ((((i * i * i) * 3) + 5) / (i * i));

對此

a[i] = a[i-1] * ((((pow(i, 3) * 3) + 5) / (i * i));

它給了我不同的結果。 為什么?

謝謝。

整數算法與浮點算法。

第一個表達式((((i * i * i) * 3) + 5) / (i * i))使用整數算術,因此使用整數除法。 第二個表達式((((pow(i, 3)) * 3) + 5) / (i * i)) ,因為pow()被定義為返回double將使用浮點算術求值,因此將返回a浮點值。 該值乘以整數a[i-1]可能會得出不同的結果,其自身會轉換回int以便存儲為a[i]

第二個循環引用尚未初始化的b[0] 整個計算取決於此值,在此之前或之后更改代碼可能會更改在沒有任何初始化的情況下碰巧存在的隨機值,並導致代碼看起來可以正常工作。 b[0]初始化為應該的值,然后再次運行測試。 為此,請使用下面的我的版本使用double算法。

對於您的問題,您應該對a[]b[]c使用double類型而不是int ,並使用強制轉換(double)將整數轉換為double ,並使用浮點常量3.05.0強制進行浮點計算:

double equation(void) {
    int n, r, s;

    printf("\nEnter the value of N: ");
    if (scanf("%d", &n) != 1) return -1;

    printf("Enter the value of R: ");
    if (scanf("%d", &r) != 1) return -1;

    printf("Enter the value of S: ");
    if (scanf("%d", &s) != 1) return -1;

    if (r < n || s < n) {
        printf("Invalid values, N must be greater or equal to noth R and S\n");
        return -1;
    }

    int i, j, k;
    double c = 0.0;
    double a[r+1], b[s+1];

    a[0] = 1.0;
    for (i = 1; i <= r; i++) {
        a[i] = a[i-1] * (((((double)i * i * i) * 3.0) + 5.0) /
                         ((double)i * i));
    }

    b[0] = 1.0; // you forgot to initialize b[0], what should it be?
    for (j = 1; j <= s; j++) {
        b[j] = b[j-1] + sqrt(3.0 * ((double)j * j * j) + j + 2.0) / (2.0 * j);
    }

    // The last for loop
    for (k = 1; k <= n; k++) {
        c += a[k] / b[k];
    }

    printf("Result: %f\n\n", c);

    return c;
}

在結果c是零不管的printf() -循環不使用或不工作printf -你是誤解了自己的調試輸出-在一個新行printf會有所幫助。 例如n=5, r=5, s=5當以下行時, n=5, r=5, s=5的輸出:

printf("*** %d, %d, %d\n", c, a[k], b[k]);

包含在循環中的是:

*** 0, 8, -144230090
*** 0, 56, -144230088
*** 0, 504, -144230086
*** 0, 6048, -144230084
*** 0, 90720, -144230082
Result: 0 

請注意, c始終為零。

問題是您正在執行整數算術運算 ,而小數部分丟失了。 整數除法會截斷小數部分,向零舍入。 例如1/2 == 0 5/2 == 2

您應該將c,a,b和函數本身的數據類型更改為兩倍。

暫無
暫無

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

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