簡體   English   中英

雙值返回 0 的操作。不明白為什么

[英]Operation with double value returning 0. Can't understand why

我正在編寫一個代碼來查找兩個雙值的諧波。 但是,我最終得到 0.0000 作為結果。 需要幫助來解決這個問題。

/*The harmonic mean of two numbers is obtained by taking the inverses of the two
numbers, averaging them, and taking the inverse of the result. Write a function that
takes two double arguments and returns the harmonic mean of the two numbers.
*/

#include <stdio.h>
double h_mean(double i,double j);
int main(void){
    double i,j;
    double hMean = h_mean(i,j);
    printf("%1f",hMean);
    return 0;
}

double h_mean(double i,double j){
    puts("Enter 2 numbers");
    scanf("%1f %1f",&i,&j);

    double inv_num = (1/i+1/j)/2;
    double inv_result = 1/inv_num;

    return inv_result;

}

使用%1f獲取浮點數可能是一個錯誤,因為您只會得到一位數。 您可能想要使用l (ell) 而不是1 (wun)。

此外,像 h_mean 這樣的h_mean應該按照它所說的去做,即計算調和平均值。 應該獲得用戶輸入,特別是因為變量是從main傳遞給它的。 你最好從類似的東西開始(用評論解釋原因):

#include <stdio.h>

// I'm a fan of DRY, so I tend to put definintions first. That
// way, I don't have to maintain definition *and* declaration.

double h_mean(double i, double j) {
    // I like explicit doubles, like 1.0. I also like spaces :-)

    double inv_num = (1.0 / i + 1.0 / j) / 2.0;
    double inv_result = 1.0 / inv_num;
    return inv_result;
}

int main(void) {
    double i, j;
    // Main should be getting input, leaving h_mean to do one thing,
    // and one thing well.
    // Also use lf (ell) rather than 1f (wun), and check that scanf
    // worked okay.
    // And I like data entry on the prompt line.

    printf("Enter 2 numbers: ");
    if (scanf("%lf %lf", &i, &j) != 2) {
        puts("Invalid input");
        return 1;
    }
    double hMean = h_mean(i, j);

    // No need for lf in printf, that's only needed for scanf.

    printf("%f\n", hMean);

    return 0;
}

使用該代碼,我得到(通過示例運行):

Enter 2 numbers: 3.14159265359 2.71828182846
2.914647

暫無
暫無

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

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