C程序输出错误
有人能找到缺陷并解释下面的程序吗?我会向大家介绍,, 1) 使用程序中的结构存储有关产品的信息。 2) 找到最低价格并显示出来。 所有工作正常,但输出未给出最低值C程序输出错误,c,function,struct,C,Function,Struct,有人能找到缺陷并解释下面的程序吗?我会向大家介绍,, 1) 使用程序中的结构存储有关产品的信息。 2) 找到最低价格并显示出来。 所有工作正常,但输出未给出最低值 #include <stdio.h> #include <malloc.h> struct product{ int code; char name[30]; float price; int qty; }; void prodata(struct product *p,in
#include <stdio.h>
#include <malloc.h>
struct product{
int code;
char name[30];
float price;
int qty;
};
void prodata(struct product *p,int n){
int i;
for (i=0;i<n;i++){
printf("\n Enter the Item Code. : ");
scanf("%d",&p[i].code);
fflush(stdin);
printf("\n Enter the Item Name. : ");
scanf("%s",&p[i].name);
printf("\n Enter the Item Price. : ");
scanf("%f",&p[i].price);
printf("\n Enter the Item Quantity in hand. : ");
scanf("%d",&p[i].qty);
}
}
void dispdata(struct product *p, int n){
int i;
int min;
min = 0;
for ( i = 1 ; i < n ; i++ ){
if (p[i].price < p[min].price) {
min = i;
}
}
printf("\n ** The Cheapest Product ** \n");
printf("\n The Product Code : %d \n",p[min].code);
printf("\n The Product Name is : %s \n",p[min].name);
printf("\n The Product Price is : %f \n",p[min].price);
printf("\n The Product Stock : %d \n",p[min].qty);
}
main(){
struct product *p=NULL;
int n;
printf("\n Product Information. \n");
printf("\n Please Enter the Number of Items : ");
scanf("%d",&n);
while(n<=1){
printf("\n Please Enter correct number of items : ");
scanf("%d",&n);
}
p =(struct product*)malloc(sizeof(struct product)*n);
prodata(p,n);
dispdata(p,n);
return 0;
}
#包括
#包括
结构产品{
int代码;
字符名[30];
浮动价格;
整数数量;
};
void prodata(结构产品*p,int n){
int i;
对于(i=0;iif(p[i]。价格
您正在将最小值设置为索引,而不是对象的实际价格。除了Daniel的回答之外,请确保索引i为0。您的for语句应该是:
for(i = 0; i < n; i++) {....
(i=0;i
现在,由于for循环从1开始计数,在我迭代到(n-1)并执行for循环中的代码块(i=0和
for(i=1
,for one和min=i
)后,您丢失的1个完整产品就结束了。您不是将价格与价格进行比较,而是将价格与循环索引进行比较。if(p[i].price
-->if(p[i]。价格
谢谢Marc。我已经做了更正,但输出仍然是错误的。谢谢danielku97,做了更正但仍然没有成功。我也会尝试Raymond的答案。Aggarwal,不知道为什么会被否决,因为这是有意义的,你将跳过你的第一个对象,因为它是基于零索引的。Raymond非常感谢你的努力。Howev呃,我正在尝试将min=0,因此我正在比较p[I]。price与p[min]。price,这是否会产生问题?输出是最后一个输入,而不是最低值。请帮助。
for(i = 0; i < n; i++) {....