2017-03-31 63 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