我创建了两个if语句进入链表,并检查有多少数字高于平均值,并查看有多少低于平均值。当我按照我的理解运行程序时,if语句只计算一个数字。此外,当程序运行时,只调用其中一个if语句,而不是两者。也许我忽略了什么?
double CalAverage (NewNumber *start){
int res;
double average = 0;
double total = 0;
int n = 1;
int x = 1;
int y = 1;
/*if (res != 1){
fprintf(stderr, "Something bad happened in CalAverage()\n");
return add;
}*/
while (start->next){
average += start->newNum;
start = start->next;
++n;
}
average += start->newNum;
total = average/n;
if(total < start->newNum){
++x;
printf("Numbers greater than average: %d\n",x);
}else if(total > start->newNum){
++y;
printf("Numbers less than average: %d\n", y);
}
printf("The average is: %lf\n",total);
return total;
return x;
return y;
}
答案 0 :(得分:1)
首先,通过在while循环中覆盖它,您将丢失指向列表开头的指针。在开始循环之前将它复制到一边。
第二,将if语句放在另一个循环中(在重新指定列表的开头之后)以计算低于/高于平均值。
double CalAverage (NewNumber *start){
double average = 0;
double sum = 0;
int n = 0;
int x = 0;
int y = 0;
NewNumber *temp = start;
while (temp){
sum += temp->newNum;
temp = temp->next;
++n;
}
average = sum / n;
temp = start;
while (temp){
if(average < temp->newNum){
++x;
}else if(average > temp->newNum){
++y;
}
temp = temp->next;
}
printf("The average is: %lf\n",average);
printf("Numbers greater than average: %d\n",x);
printf("Numbers less than average: %d\n", y);
return average;
}
答案 1 :(得分:0)
if语句不在while循环中,因此函数启动,while循环完成,然后只调用一个if语句,因为它是if,elseif