2013-08-27 31 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,因为它是浮点型变量。