所以我想編寫一個程序,提示用戶輸入用戶希望擁有多少數據集,也就是將有多少個數組。然後它會提示用戶輸入每個數據集中有多少個值以及這些值是多少。最後,它爲用戶提供了在所需數據集上運行的選項列表。C將數字列表讀入多個數組
當我運行我的代碼並選擇要使用的數據集時,它似乎總是拿出最後一個數據集並且似乎沒有集合中的所有值。我只是想知道,如果有人能讓我知道我做錯了什麼,或者至少讓我走上正軌。我已經多次閱讀代碼並且無法弄清楚。
#include <stdio.h>
int main()
{
unsigned short int num_sets, set_size, set_desired, command = 0;
printf("Enter the number of data sets you would like to store: ");
scanf(" %hu", &num_sets);
int i = 1, j, sets[1][num_sets], sum, a;
while(i <= num_sets)
{
j = 1;
printf("Enter the number of elements in data set %hu: ", i);
scanf(" %hu", &set_size);
printf("Enter the data for set %hu: ", i);
while(j < set_size)
{
scanf(" %d", &sets[i - 1][j - 1]);
j++;
}
i++;
}
printf("Which set would you like to use?: ");
scanf(" %hu", &set_desired);
while(set_desired > num_sets){
printf("There aren't that many data sets, try again: ");
scanf(" %hu", &set_desired);
}
printf("Set #%hu: %hu\n", num_sets, *sets[num_sets - 1]);
while(command != 7){
printf("Choose what you would like to do:\n");
printf("1. Find the minimum value.\n");
printf("2. Find the maximum value.\n");
printf("3. Calculate the sum of all the values.\n");
printf("4. Calculate the average of all the values.\n");
printf("5. Sort the values in ascending order.\n");
printf("6. Select a different data set.\n");
printf("7. Exit the program.\n");
scanf(" %hu", &command);
if(command == 1){
printf("You picked 1!");
}
if(command == 2){
printf("You picked 2!");
}
if(command == 3){
/*printf("You picked 3!");
for(a = 0; a < set_size; a++){
sum = sum + *sets[a];
}
printf("%d\n", sum);*/
printf("You picked 3!");
}
if(command == 4){
printf("You picked 4!");
}
if(command == 5){
printf("You picked 5!");
}
if(command == 6){
printf("You picked 6!");
}
if(command == 7){
break;
}
}
}
使用'set_desired'可以幫助(不知道你的意思做的'的printf( 「設置#%胡:胡%\ n」,num_sets,*套[num_sets-1]) '在得到'set_desired'後......)。另外,將每個set的'set_size'存儲到一個數組中(因爲它們可能有不同的大小)可能是一個好主意。 – SleuthEye 2014-09-25 02:34:58
在隨後調用'fscanf'之前,您可能還會遇到輸入緩衝區未刷新的問題。如果是這種情況,那麼在每個'fscanf'之後清空輸入緩衝區。創建一個int'int c;',然後在每次使用'fscanf'後用'do {c = getchar; } while(c!='\ n'|| c!= EOF);' – 2014-09-25 03:08:32
由於某種原因,sets'定義爲:sets [1] [num_sets](整數的二維數組)如:*設置[num_sets - 1]這是一個單維數組。這行還有其他一些問題,例如,即使編譯正確(不太可能),也只會打印一個整數。 – user3629249 2014-09-25 07:58:13