仅计算正分数并将平均值结果从整数更改为浮点

标签 c

这是我的 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/

相关文章:

c - 使函数根据参数选择接口(interface)

c - 如何编写给定数组的所有组合

c - 如何在 C 预处理器中使用复杂的控制流、算术或函数原语?

c - GetProcessioCounters : Error Invalid access to memory location

c - 在 shell 上的这个 C 程序中为什么会出现段错误错误

c - 为什么负值会给从具有给定总和的数组中查找值对的程序带来段错误?

c - 在 Windows 上为 Haskell 构建 GD 库时出现 ld 错误

c - Windows 函数的链接错误

python - 如何在python程序中嵌入C代码?

C 模拟终端