#include<stdio.h>
int main(){
float a[100],sum=0.0,avg,havg[100],min,max;
int i;
for(i=0; i!=-1;i++){
printf("Enter number : ");
scanf("%f",&a[i]);
max = a[0];
min = a[0];
sum+=a[i];
avg= sum/(i+1);
havg[i]=avg/2;
printf("Loop %d Summation : %.0f ",i,sum);
printf("Half of Avg. : %.2f \n",havg[i]);
for(int j=0; j<i; j++){
if (a[i]>max) {
max = a[i];
}
if (a[i]<min) {
min = a[i];
}
}
if(a[i]>havg[i-1]&&i!=0){
break;
}
}
printf("---Data Complete---\n");
printf("Max: %.0f\n", max);
printf("Min: %.0f\n", min);
这里的输出是:
输入数字:24
循环0的总和:平均水平的24 :12.00
输入数字:12
循环1的总和:平均一半的36。 :9.00
输入数字:-5
循环2的总和:平均31的一半:5.17
输入数字:9
循环3的总和:平均一半的40。 :5.00
---数据完成---
最大:24
最小值:9
我已经在Google数组中查找了最小值和最大值。我想我搞砸了:
#include<stdio.h>
int main(){
float a[100],sum=0.0,avg,havg[100],min=0.0,max=0.0;
int i;
for(i=0; i!=-1;i++){
printf("Enter number : ");
scanf("%f",&a[i]);
max = a[0];
min = a[0];
sum+=a[i];
avg= sum/(i+1);
havg[i]=avg/2;
printf("Loop %d Summation : %.0f ",i+1,sum);
printf("Half of Avg. : %.2f \n",havg[i]);
if (a[i]>max){
max = a[i];
}
if (a[i]<min){
min = a[i];
}
if(a[i]>havg[i-1]&&i!=0){
break;
}
}
printf("---Data Complete---\n");
printf("Max: %.0f\n", max);
printf("Min: %.0f\n", min);
}
所以现在我用不同的数字进行测试(首先从负数开始)
Enter number : -10
Loop 1 Summation : -10 Half of Avg. : -5.00
Enter number : -90
Loop 2 Summation : -100 Half of Avg. : -25.00
Enter number : 30
Loop 3 Summation : -70 Half of Avg. : -11.67
---Data Complete---
Max: 30
Min: -10
这真是令人困惑
答案 0 :(得分:0)
请移动min
和max
初始化,在每个循环中完成
#include<stdio.h>
int main(){
float a[100],sum=0.0,avg,havg[100],min=0.0,max=0.0;
int i;
for(i=0; i!=-1;i++){
printf("Enter number : ");
scanf("%f",&a[i]);
sum+=a[i];
avg= sum/(i+1);
havg[i]=avg/2;
printf("Loop %d Summation : %.0f ",i+1,sum);
printf("Half of Avg. : %.2f \n",havg[i]);
if(i == 0) {
max = a[0]; // moved to here
min = a[0];
}
else {
if (a[i]>max){
max = a[i];
}
if (a[i]<min){
min = a[i];
}
if(a[i]>havg[i-1]) { // moved this too
break;
}
}
}
printf("---Data Complete---\n");
printf("Max: %.0f\n", max);
printf("Min: %.0f\n", min);
}
程序输出:
Enter number : -10 Loop 1 Summation : -10 Half of Avg. : -5.00 Enter number : -90 Loop 2 Summation : -100 Half of Avg. : -25.00 Enter number : 30 Loop 3 Summation : -70 Half of Avg. : -11.67 ---Data Complete--- Max: 30 Min: -90