-3
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
int n, i, input_cases,x;
scanf("%d", &input_cases);
float *results = malloc(input_cases*sizeof(float));
for (x=0; x<input_cases; x++){
float num[100], sum[2] = {0.0}, average[2] = {0.0};
printf("Enter the total amount of numbers: ");
if (scanf("%d", &n) != 1) { /* validates input */
fprintf (stderr, "error: invalid input.\n");
return 1;
}
for (i = 0; i < n; i++) {
if (scanf("%f", &num[i]) != 1) { /* validate input */
fprintf (stderr, "error: invalid input.\n");
return 1;
}
}
/* sum/average 1st-half */
for (i = 0; i < n/2; ++i){
sum[0] += num[i];
average[0] = sum[0] * 2/n;
}
/* sum/average 2nd-half */
for (i = n/2; i < n; ++i){
sum[1] += num[i];
average[1] = sum[1] * 2/n;
}
if (average[0]>average[1]){
results[x]=average[0];
printf("%.6f\n", average[0]);
}
else{
results[x]=average[1];
printf("%.6f\n", average[1]);}
}
for (x=0; x<input_cases; x++){
printf("%.6f\n", results[x]);
free(results);
}
return 0;
}
這是我的代碼呢:如何在最後一次輸出結果,而不是在使用for循環時逐一輸出結果?
Input:
2
Enter the total amount of numbers: 10
10
8
9
15
12
2
3
8
7
11
10.800000(This is the output)
Enter the total amount of numbers: 4
3
3
2
1
3.000000(This is the output)
10.800000(My output when i dynamically allocate an array to display everything at the end)
0.000000(My output when i dynamically allocate an array to display everything at the end)
這是我真正想要的樣子:
Input:
2
Enter the total amount of numbers: 10
10
8
9
15
12
2
3
8
7
11
Enter the total amount of numbers: 4
3
3
2
1
Output:
10.800000
3.000000
我怎麼能採取什麼樣的,我從我的計算了,並讓他們所有輸出都在最後,而不是在每次計算結束時單獨輸出每個輸出?
將答案保存在數組中(您可能必須動態增長)。當你完成所有工作後,迭代數組並將它們全部打印出來。 –
@TomKarzes我試過這樣做,但是當我打印出該數組時,我的值變爲0。我知道我動態分配時做錯了什麼,但我不知道什麼.... – UcfKnight
你做錯了什麼,但我不禁要看到代碼。 –