-5
#include<stdio.h>

int main()  
{  
    char name[3];  
    float price[3];  
    int pages[3];  
    int i;  
    for(i=0; i<3; i++)  
    {
        printf("enter the title, price and pages of three books\n");  
        fflush(stdin);  
        scanf("%c %f %d", &name[i], &price[i], &pages[i]);  
        printf("the value of i is %d\n", i);  
    }  

   for(i=0; i<3; i++)
   {
       printf("the title of the book is %c, price of the book is %f,   
       number of pages of the book is %d", name[i], price[i], pages[i]);  
   }  

   return 0;  
}  

我得到的输出是:

the title of the book is a, price of the book is 122.000000, number of pages of the book is 22
the title of the book is , price of the book is 0.000000, number of pages of the book is 134520820
the title of the book is b, price of the book is 0.000000, number of pages of the book is -10

我想要得到的是:

the title of the book is Harry Potter, price of the book is 20, number of pages of the book is 22

the title of the book is 50 shades of grey, price of the book is 30, number of pages of the book is 60

the title of the book is Game of Thrones, price of the book is 40, number of pages of the book is 200
4

3 回答 3

2

对您的代码进行以下更改。

  1. 更改char name[3];char name[3][100];每个条目最多容纳 100 个字符。

  2. 不要这样做fflush(stdin);。因为它是未定义的行为

  3. scanf(" %s %f %d", name[i], &price[i], &pages[i]);

  4. 也使用%s而不是%c在 printf() 中。%c 仅用于单个字符。

于 2013-07-17T07:11:48.627 回答
0

进行以下更改,您将不会出错。

for(i=0; i<3; i++)  
    {
       printf("enter the title, price and pages of three books");
       scanf("%c",&name[i]);
       scanf("%f",&price[i]);    
       scanf("%d",&pages[i]);
     }

您的其余代码都可以!

于 2013-07-18T12:11:51.477 回答
0

用这个替换你的 scanf 行并再次运行它,它将运行良好并观察差异
scanf("%s%f%d",&name[i],&price[i],&pages[i]);

于 2013-07-17T07:11:49.407 回答