我正在为杂货店库存编写一个接受输入的代码,需要数量和价格来计算价值,并在用户输入0后停止但是当我输入第一个数字后编译它说“#34;分段错误"”。我该如何解决这个问题?
#include<stdio.h>
#define MAX 100
void show();
int main(void){
long long Barcode[MAX];
int Quantity[MAX], i, k, Counter;
float Price[MAX], Value[MAX], Total;
Counter=0;
show();
do {
printf("Barcode : ",i);
scanf("%lld", &Barcode[i]);
printf("Price : ",i);
scanf(" %f",&Price[i]);
printf("Quantity: ",i);
scanf(" %d",&Quantity[i]);
Counter++;
} while (Barcode !=0 && Counter !=MAX);
for(i=0; i<Counter; i++) {
Value[i] = (Quantity[i] * Price[i]);
}
printf(" Goods In Stock ");
printf("Barcode Price Quantity Value");
printf("\n----------------------------------------------\n");
for(k=0; k<Counter; k++) {
printf("%-10lld",Barcode[k]);
printf("%5.2f",Price[k]);
printf("%8d",Quantity[k]);
printf("%5f",Value[k]);
}
printf("%8c------",' ');
printf("\nTotal Value of goods in stock ");
return 0;
}
void show() {
printf("Grocery Store Inventory ");
printf("\n-----------------------\n");
}
答案 0 :(得分:2)
尝试始终初始化变量(除非您知道自己在做什么):
long long Barcode[MAX];
int Quantity[MAX], i=0, k=0, Counter=0;
float Price[MAX], Value[MAX], Total=0;
答案 1 :(得分:2)
您使用具有自动存储持续时间的未初始化变量i
的值来调用未定义行为,这是不确定的。
这部分代码
do {
printf("Barcode : ",i);
scanf("%lld", &Barcode[i]);
printf("Price : ",i);
scanf(" %f",&Price[i]);
printf("Quantity: ",i);
scanf(" %d",&Quantity[i]);
Counter++;
} while (Barcode !=0 && Counter !=MAX);
应该是
do {
i = Counter; /* assign Counter to i, so that i used here will have the correct value */
printf("Barcode : ",i);
scanf("%lld", &Barcode[i]);
printf("Price : ",i);
scanf(" %f",&Price[i]);
printf("Quantity: ",i);
scanf(" %d",&Quantity[i]);
Counter++;
/* Barcode != 0 will be alway true. Do you mean Barcode[i] != 0 ? */
/* Note that using Barcode[Counter] != 0 is wrong here because Counter is incremented
* and Barcode[Counter] will be uninitialized or out-of-range */
} while ( Barcode[i] != 0 && Counter !=MAX);