7

私はCを学ぼうとしていて、次の小さなプログラムを考え出しました。

#include "stdafx.h"

void main()
{
    double height = 0;
    double weight = 0;
    double bmi = 0;

    printf("Please enter your height in metres\n");
    scanf_s("%f", &height);
    printf("\nPlease enter your weight in kilograms\n");
    scanf_s("%f", &weight);
    bmi = weight/(height * height);
    printf("\nYour Body Mass Index stands at %f\n", bmi);
    printf("\n\n");
    printf("Thank you for using this small program.  Press any key to exit");
    getchar();
    getchar();
}

プログラムは完全にコンパイルされますが、プログラムによって返される答えは意味がありません。高さを1.8、体重を80とすると、bmiは1.#NF00のようになり、意味がありません。

私は何が間違っているのですか?

4

6 に答える 6

11

When using scanf with a double, you must use the %lf specifier, as pointers are not promoted with scanf.

For more info, read the following question: Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

于 2012-07-26T14:44:21.930 に答える
10

scanf(およびscanf_s) format%fは type へのポインタを想定していますfloat

これを修正するにはheightweight変数のタイプを に変更するだけです。float

于 2012-07-26T14:43:17.550 に答える
4

scanf_s構文の問題は、バッファのサイズ(バイト単位)である3番目の引数を省略したことだと思います。次のことを試してください。

scanf_s("%lf", &valueToGet, sizeof(double));
于 2012-07-26T14:45:45.633 に答える
3

scanf() と printf() の欠点は、非常に厳密な形式が必要なことです。制御文字列と引数が一致しないと、入力または出力がまったく意味をなさないような重大なエラーが発生する可能性があります。そして、その間違いは初心者が犯すことがよくあります。

于 2012-07-27T11:56:42.960 に答える
2

%f書式指定子を使用している場合は、double ではなく float データ型を使用する必要があります。

于 2014-01-13T20:37:11.077 に答える
0

問題は次の理由によるものです。

format '%f' expects argument of type 'float*', but argument 2 has type 'double*' 

これを処理するには、次の 2 つの方法があります。

  1. 変数は次のいずれかである必要がありますfloat

    double height = 0;    -->    float height = 0;
    double weight = 0;    -->    float weight = 0;
    double bmi = 0;       -->    float bmi = 0;
    
  2. または にformat specifier対応する必要がありdoubleます。

    scanf_s("%f", &height);   -->    scanf_s("%lf", &height);
    
    scanf_s("%f", &weight);   -->    scanf_s("%lf", &weight);
    
    printf("\nYour Body Mass Index stands at %f\n", bmi);
                                              |
                                              V 
    printf("\nYour Body Mass Index stands at %lf\n", bmi);
    
于 2015-06-01T05:24:21.127 に答える