0

以下のプログラムでは、から値を取得していませんprintf

#include<stdio.h>

int main()
{
    struct book
    {
        char name;
    float price;
    int pages;
    };
    struct book b1,b2,b3;

    printf("enter names prices & no. of pages of 3 books\n");
    scanf("%c %f %d",&b1.name,&b1.price,&b1.pages);
    fflush(stdin);
    scanf("%c %f %d",&b2.name,&b2.price,&b2.pages);
    fflush(stdin);
    scanf("%c %f %d",&b3.name,&b3.price,&b3.pages);
    fflush(stdin);
    printf("and this is what you entered\n");
    printf("%c %f %d",&b1.name,&b1.price,&b1.pages);
    printf("%c %f %d",&b2.name,&b2.price,&b2.pages);
    printf("%c %f %d",&b3.name,&b3.price,&b3.pages);
    return 0;
}

そして私が得ているこの出力

enter names prices & no. of pages of 3 books
a 34.6 23
b 23.4 34
c 63.5 23

and this is what you entered

0.000000 0∞ 0.000000 0╪ 0.000000 0Press any key to continue . . .

出力が入力と一致しないのはなぜですか?

4

2 に答える 2

3
printf("%c %f %d",&b1.name,&b1.price,&b1.pages);
printf("%c %f %d",&b2.name,&b2.price,&b2.pages);
printf("%c %f %d",&b3.name,&b3.price,&b3.pages);

あまりにも多くのコピーアンドペーストメチンク。floatとintについても同じように、sを printf期待するときにポインタを渡します。char

scanf関数がそれらの値を変更できるように、これらの変数のアドレスをに渡しました。、、を使用%dし、int(intへのポインターではない)、float(floatへのポインターではない)、およびchar(charへのポインターではない)を期待する%f場合。%c printf

于 2012-06-22T04:06:20.123 に答える
2

プログラムには複数の問題があります。

  • char1文字に収まります。本のタイトルを保存するのに十分な大きさではありません。
  • アドレスをscanfに渡しますが、値をに渡しますprintf(つまり、&printfパラメータを除いて、のパラメータにはありません%p
  • fflush入力ストリームを入力する必要はありません。効果はありません。

私はあなたが(またはあなたが好む他の最大サイズ)に、そしてのために変更char nameするべきだと思います。アンパサンドがどのように欠落しているかに注意してください。これは、Cの関数に渡されると、配列がポインターに減衰するためです。char name[101]scanf("%c...", &b1.name,...)scanf("%100s...", b1.name,...)&b1.name

于 2012-06-22T04:06:29.913 に答える