我正在为大学研讨会创建一个程序。我差不多完成了,但是当我编译我的程序并运行它时,它的工作方式不符合它: 这是我的代码:
#include <stdio.h>
int calulation(long long int barcode[100], double price[100], int quantity[100], int i);
int main(void) {
long long int barcode[100];
double price[100];
int quantity[100];
int i;
printf("Grocery Store Inventory \n");
printf("======================= \n");
printf("Barcode: ");
scanf("%lld", &barcode[0]);
printf("Price: ");
scanf("%f", &price[0]);
printf("Quantity: ");
scanf("%d", &quantity[0]);
for (i = 0;i < 99; i++) {
printf("Barcode: ");
scanf("%lld", &barcode[i]);
if (barcode[i] == 0) {
break;
}
printf("Price: ");
scanf("%f", &price[i]);
printf("Quantity: ");
scanf("%d", &quantity[i]);
}
calculation(barcode, price, quantity, i);
}
int calculation(long long int barcode[], double price[], int quantity[], int i) {
double totalAmount;
int j;
printf("Goods in Stock \n");
printf("===============\n");
//j count and display entered value as long as it is less than i
for (j=0;j<i+1;j++) {
printf(" %lld, %.2f, %d, %.2f \n", barcode[j], price[j], quantity[j]);
}
//All prices are added for totalamount
for(j = 0; j < i+1; j++) {
totalAmount = price[j] + price[j];
}
//totalamount is multiplied by quantity for the final price
for (j = 0; j < i+1; j++) {
totalAmount = totalAmount * quantity[j];
}
printf("Total value goods in stock: %.2f \n", totalAmount);
}
问题是当我运行程序并输入所有数据时输出不正确。输出是这样的:
Grocery Store Inventory
=======================
Barcode: 123
Price: 1.24
Quantity: 4
Barcode: 1234
Price: 2.24
Quantity: 8
Barcode: 12345
Price: 0.40
Quantity: 20
Barcode: 0
Goods in Stock
===============
1234, 2.24, 8, -0.00
12345, 0.40, 20, -0.00
0, -0.00, 0, -0.00
Total value goods in stock: -0.00
我们输入条形码,价格和数量,当条形码为0时,程序结束。
答案 0 :(得分:1)
“scanf(”%f“,&amp; price [0])”
价格是一系列双打。您应该将%lf与scanf一起使用。
在for
循环中,您会覆盖条形码[0],数量[0],价格[0]。
在你的计算函数中,在第一个循环中你不需要最后的%.2f,因为你只有三个变量。这就是你获得-0.00的原因。
在计算功能的第二个for
循环中,您将产品的价格相加并乘以2.
然后在第三个for
循环中,将所有产品的总价格乘以每个产品的数量。这毫无意义。
您可能想要这样做:
double sum = 0;
将此行放入第二个for
循环并删除第三个for
循环:
sum += price[j]*quantity[j];
答案 1 :(得分:0)
price
是double
的数组。你应该使用:
scanf("%lf", &price[0]);
在这一行
printf(" %lld, %.2f, %d, %.2f \n", barcode[j], price[j], quantity[j]);
你有4个标识符,但只有3个变量。
答案 2 :(得分:0)
你有两组三次scanf()调用,一次是索引0,然后是99次,从索引0开始。所以你输入的第一组数据总是被第二组覆盖。
答案 3 :(得分:0)
printf("Quantity: ");
scanf("%d", &quantity[0]);
for (i = 1; i < 99; i++) {
printf("Barcode: ");
scanf("%lld", &barcode[i]);
您读取位置0然后再次读取,因此i = 1
是正确的
calculation(barcode, price, quantity, i-1);
您在条形码上以i结束for
循环,其值为0,因此有效值为i-1:
printf(" %lld, %.2f, %d \n", barcode[j], price[j], quantity[j]);
你想要打印4个vlaues,但为什么当你需要3:
for( j = 0; j < i+1; j++) {
totalAmount = totalAmount + (price[j]*quantity[j]);
}
可能你想要为一种类型的物体增加数量。