1

このちょっとしたCコードは、私を苛立たせています。入力電圧を要求しますが、抵抗1をスキップして、抵抗2を要求します。ここで非常に明白な何かが欠落しています...一体何が起こっているのか...

#include <stdio.h>
int main() 
{
    float Vin;
    int R1;  
    int R2;

    printf("Input Voltage: ");
    scanf("%.3f", &Vin);

    printf("\nResistor 1: ");
    scanf("%d", &R1);

    printf("\nResistor 2: ");
    scanf("%d", &R2);

    return(0);
}
4

4 に答える 4

5

パーツを取り外します.3

scanf("%f", &Vin);

入力の小数点以下の桁数を設定することは実際には意味がありません:)したがって、scanfそれをサポートしていません。Afloatは常に10進数で8桁です。コンパイラの警告レベルを上げます。

于 2013-02-01T22:18:08.917 に答える
5

コンパイラをオンに-Wallすると、次の警告が表示されます。

警告:不明な変換タイプの文字'。' フォーマット[-Wformat]

警告:フォーマットの引数が多すぎます[-Wformat-extra-args]

したがって、.3を。から削除するだけscanfです。

于 2013-02-01T22:18:52.693 に答える
3

単純な%fを使用します。サンプルは次のとおりです。

printf("Input Voltage: ");
scanf("%f", &Vin);

printf("\nResistor 1: ");
scanf("%d", &R1);

printf("\nResistor 2: ");
scanf("%d", &R2);
于 2013-02-01T22:17:07.157 に答える
3

Shooting from the hip here - my gut says that the first scanf is being "satisfied" by your input string, there's input left over, and the second scanf is getting everything up to the newline.

Try replacing the first format string in with "%f" and see whether it still happens. Alternatively, print out the values of voltage and R1 when you see the goofy behavior. It's probably better to worry about rounding/truncating the voltage input after you read it, anyway.

于 2013-02-01T22:19:21.580 に答える