2017-03-31 53 views
0

这里是我的代码:不能修改C编程结构阵列的成员值

#include <stdio.h> 
struct book 
    { 
     char bookID[20]; 
     char name[20]; 
     double price; 
    }; 

void input(struct book bs[], int n) 
{ 
    for (int i = 0; i < n; i++) 
    { 
    printf("Please input the price of book %s:\n",bs[i].name); 
    scanf("%f",&bs[i].price); 
    } 
} 

void print(struct book bs[], int n) 
{ 
    for (int i = 0; i < n; i++) 
    { 
     printf("%s\t%s\t%.2f\n", bs[i].bookID, bs[i].name, bs[i].price); 
    } 
} 

int main(void) 
{ 
    book books[4] = {{"0101","Computer",1.5},{"0102","Programming",4.1},{"0103","Math",3.3},{"0104","English",1.2}};  
    input(books, 4); 
    print(books, 4); 
    return 0; 
} 

但是,当我输入的四本书任何代价,打印功能始终输出默认值:1.5,4.1, 3.3,1.2

想知道是哪里不对。谢谢!

+2

'的scanf( “%F”,&BS [I]。价格);' - >'的scanf( “%LF”,&BS [I]。价格);' –

回答

2

您在您的代码中有未定义的行为,因为您使用错误的scanf格式读取double

的正确格式为scanfdouble"%lf"


注意,对于printf不要紧,"%f""%lf"都是有效的floatdouble