私はワイン醸造所からの注文情報を含むテキストファイルからの入力を読み込むプログラムを書く必要がある、Cクラスの紹介のためにいくつかの宿題に取り組んでいます。私はすべてを書きましたが、私がそれを実行すると、注文総コストの数学はオフになります。昨夜、このプログラムの配列をいくつかのユーザーから修正する助けがありましたが、今では何が数学的なエラーを引き起こしているのかよく分かりません。これは私が持っているコードです: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
これは、入力ファイル「ワインからのデータです。 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
また、必要な場合は)私の数学エラーが唯一のコードを指摘することができますが、私は明確にするためにこれを含めることirely可能性、これは、入力ファイル内の各整数が何を表すかの私の教授の説明です:
の最初の行各テストケースには、そのワイナリーからのワインの可能性のある異なるボトルの数を表す単一の正の整数k(k≦10)が含まれます。各テストケースの2行目には、そのワイナリーでワインの各タイプのコストをスペースで区切って表すk個の正の整数が入ります。各テストケースの3行目には、処理するワイナリーの注文数を表す1つの正の整数c(c < 10)が含まれます。次のc行にはそれぞれ、その順序の各タイプのボトルの数を表すk個の整数が含まれます。
質問の長さをお詫び申し上げますが、わかりやすくするために必要なすべての情報を提供しています。いつものように、私は大いに助けてくれています。
'prices [num_bottles]'は未定義です。 C配列は '[0:n]'であることを覚えておいてください – Anycorn
長い質問はもっと不明です...そのパラドックスです! – hugomg
まず、 'int prices [num_bottles]'を作成すると、 'num_bottles - 1'がその配列の最大インデックスになります。さらに、 'num_bottles'が実際にその計算の中で使用したいインデックスであるかどうかを再評価するべきだと私は思っています。 – jpm