2013-08-27 68 views
2

我試圖運行的功能實現與結構在C ... ...這是一個程序,怎麼被初始化:結構變量亙古在C

#include<stdio.h> 
#include<conio.h> 
struct store 
    { 
    char name[20]; 
     float price;  
     int quantity; 
    }; 

struct store update (struct store product, float p, int q); 

float mul(struct store stock_value); 


    main() 
{ 
    int inc_q; 
    float inc_p,value; 

    struct store item = {"xyz", 10.895 ,10}; //## this is where the problem lies ## 


    printf("name = %s\n price = %d\n quantity = %d\n\n",item.name,item.price,item.quantity); 

    printf("enter increment in price(1st) and quantity(2nd) : "); 
    scanf("%f %d",&inc_p,&inc_q); 

item = update(item,inc_p,inc_q); 

    printf("updated values are\n\n"); 
    printf(" name  = %d\n price  = %d\n quantity = %d",item.name,item.price,item.quantity); 

    value = mul(item); 

    printf("\n\n value = %d",value); 
} 
struct store update(struct store product, float p, int q) 
{ 
    product.price+=p; 
    product.quantity+=q; 
    return(product); 
}  
float mul(struct store stock_value) 
{ 
    return(stock_value.price*stock_value.quantity); 
} 

當我初始化該結構存儲項= {」 xyz「,10.895,10};不被存儲在由部件的值,即本亞特(結構存儲項)線路成員:

  1. item.name「XYZ」

  2. 項。價格應該10.895

  3. item.quantity應該是;

但除了的item.name = XYZ其他成員採取自己的垃圾..我無法理解這個行爲... 我使用devC++(版本5.4.2與mingw)...

我得到的問題,因爲我使用char名稱[20]作爲結構存儲的成員?

有人請有助於消除錯誤在我的代碼..回覆很快

+0

發佈你正在得到的輸出.. –

+0

除了不適當的'printf',請考慮閱讀本文http://stackoverflow.com/questions/330793/how-to-initialize-a-struct-in-ansi-c – Aneri

+0

我不知道你可以指定一個這樣的結構。 – Jiminion

回答

10

您正在使用%d格式說明打印float,這是不確定的行爲。你應該使用浮點數%f,整數使用%d。對於您的代碼,應該是:

printf("name = %s\n price = %f\n quantity = %d\n\n", 
     item.name, item.price, item.quantity); 

因爲item.price是一個浮點數。

在稍後的printf中,您還正在使用%d來打印字符串item.name。應改爲%s

+0

對於那些不知道,'%f'是'float'和'double'的正確格式(因爲'float' 'printf'的參數被提升爲'double')。 –

+0

@interjay,你好。我在8月25日才明白它..謝謝你的回覆...這真的是一個愚蠢的錯誤...... –

1

請注意,item.quantity將給出10.然後將%d更改爲%f對於item.price,因爲它是浮點型變量。