这是我的 C 代码,我需要帮助如何忽略 printf("You Entered %d Scores.\n", i); 和 中的负数>平均结果。
还有如何将intaverage;更改为floataverage;,因为当我更改它时我没有得到正确的平均值浮。
这是我的代码:
int main()
{
int i, score, sum=0, n;
int average;
for(i=0; score>0; i++)
{
printf("Enter score (4-10) :");
scanf("%d", &score);
if(score>0){
sum = sum + score;
}
}
printf("You entered %d scores.\n", i);
average = sum / i;
printf("the average is: %d", average);
}
所需的输出:
程序会计算您输入的分数的平均值。
以负整数结尾。
输入分数(4-10):7
输入分数(4-10):8
输入分数(4-10):9
输入分数(4-10):10
输入分数(4-10):4
输入分数(4-10):4
输入分数(4-10):5
输入分数(4-10):-1
您输入了 7 个分数。
平均分:6.71
最佳答案
看来平均值、总和和分数都应该是小数值( float )。
这意味着您还必须更改 scanf 参数和 printf 参数。
当整数i除以 float sum时,不需要乘以1.0,只要sum是 float 即可。
#include <stdio.h>
int main()
{
int i;
float score;
float sum = 0;
float average;
for (i = 0; score > 0; i++) {
printf("Enter score (4-10) :");
scanf("%f", &score); // accept decimals in the scores
if (score > 0) {
sum = sum + score;
} else {
break; /// leave the loop here to prevent incrementing i
}
}
printf("You entered %d scores.\n", i);
average = sum / i; // as sum is a float, this division will now work.
printf("the average is: %2.2f", average); // print 2 decimal places as a float
}
关于仅计算正分数并将平均值结果从整数更改为浮点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55432232/