【发布时间】:2012-03-27 22:12:27
【问题描述】:
我正在做一些 C 类介绍的家庭作业,其中我们必须编写一个程序,该程序从包含酒厂订单信息的文本文件中读取输入。我已经把所有东西都写出来了,但是当我运行它时,订单总成本的数学计算是错误的。昨晚我从一些用户那里得到了一些修复这个程序中的数组的帮助,但现在我不太确定是什么导致了数学错误。这是我的代码:
int main () {
//Creates the file pointer and variables
FILE *ifp;
int index, index2, index3, index4;
int wineries, num_bottles, prices, orders, sum_order, total_orders;
//Opens the file to be read from.
ifp = fopen ("wine.txt", "r");
//Scans the first line of the file to find out how many wineries there are,
//thus finding out how many times the loop must be repeated.
fscanf(ifp, "%d", &wineries);
//Begins the main loop which will have repititions equal to the number of wineries.
for (index = 0; index < wineries; index ++) {
//Prints the winery number
printf("Winery #%d:\n", index + 1);
//Scans the number of bottles at the aforementioned winery and
//creates the array "prices" which is size "num_bottles."
fscanf(ifp,"%d", &num_bottles );
int prices[num_bottles];
//Scans the bottle prices into the array
for (index2 = 0; index2 < num_bottles; index2++)
fscanf(ifp, "%d", &prices[num_bottles]);
//Creates variable orders to scan line 4 into.
fscanf(ifp, "%d", &orders);
for(index3 = 0; index3 < orders; index3++){
int sum_order = 0;
for(index4 = 0; index4 < num_bottles; index4++)
fscanf(ifp, "%d", &total_orders);
sum_order += (prices[num_bottles] * total_orders);
printf("Order #%d: $%d\n", index3+1, sum_order);
}
printf("\n");
}
//printf("%d", prices[index2]);
fclose(ifp);
return 0;
}
当我运行程序时,会打印出以下内容:
酒厂#1
订单 #1:150 美元
订单 #2:60 美元
订单 #3:60 美元
订单 #4:$0
酒厂#2
订单 #1:$0
什么时候应该打印出来:
酒厂#1
订单 #1:160 美元
订单 #2:200 美元
订单 #3:120 美元
订单 #4:40 美元
酒厂#2
订单 #1:40 美元
这是来自输入文件“wine.txt”的数据:
2
3
10 20 30
4
1 0 5
8 3 2
2 2 2
4 0 0
5
17 27 44 54 75
1
1 2 0 0 0
如果有必要(我认为我的数学错误完全有可能仅通过代码指出,但为了清楚起见,我想将其包括在内),这是我的教授对输入文件中每个整数的解释代表:
每个测试用例的第一行将包含一个正整数 k (k ≤ 10),表示来自该酒厂的不同瓶装葡萄酒的数量。每个测试用例的第二行将包含 k 个正整数,表示该酒厂每瓶葡萄酒的成本,用空格分隔。每个测试用例的第三行将包含一个正整数 c (c
对于问题的长度,我深表歉意,我只是想确保我提供了所有必要的信息,以便清楚起见。与往常一样,我非常感谢您的帮助,因为你们在 stackoverflow 继续让我变得更容易。
【问题讨论】:
-
prices[num_bottles]未定义。记住 c 数组是[0:n) -
但长问题更不清楚......这是一个悖论!
-
对于初学者,当您创建
int prices[num_bottles]时,num_bottles - 1是该数组中的最大索引。此外,我认为您应该重新评估num_bottles是否真的是您要在该计算中使用的索引。 -
jpm,是什么导致数组的最大索引为 -1?我真的觉得这很令人困惑。