#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;
}
这就是我的代码所做的:
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
我怎样才能从计算中得到我最后输出的所有内容,而不是在每次计算结束时分别输出每一项?
答案 0 :(得分:1)
打印完所有值后,您应public class MyActivity extends Activity {
private static final int PROGRESS = 0x1;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.progressbar_activity);
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
}).start();
}
}
free
。但是你在打印第一个值后array
犯了free
这个错误。我认为你明白了。
array