r_g*_*yal 2 c struct initialization char
我正在尝试运行一个程序,实现一个带有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);
}
Run Code Online (Sandbox Code Playgroud)
当我初始化struct store item = {"xyz",10.895,10}时; 这些值不是由成员存储的,即ater(struct store item)行成员:
item.name应为"xyz",
item.price应该是10.895,
item.quantity应为10 ;
但除了在 item.name = XYZ 其他成员采取了 垃圾 自身的价值..我无法理解这个行为...我使用DEVC++(使用MinGW 5.4.2版)...
我遇到问题因为我使用char name [20]作为struct store的成员???
请帮忙删除我的代码中的错误..很快回复
int*_*jay 10
您正在使用%d格式说明符来打印a float,这是未定义的行为.你应该使用%f浮点数和%d整数.对于您的代码,应该是:
printf("name = %s\n price = %f\n quantity = %d\n\n",
item.name, item.price, item.quantity);
Run Code Online (Sandbox Code Playgroud)
因为item.price是一个浮动.
稍后printf您还可以使用%d打印字符串item.name.它应该改为%s.