为什么我的平均值不是正确的答案? (C代码程序找到意思)

时间:2017-06-22 23:11:36

标签: c floating-point output average mean

我正在抨击我,因为我无法弄清楚为什么我的C代码会一直打印出一组n个数字的错误平均值!

这是我的代码:

int main()
{
    int i;
    int n;
    int sum = 0.0;
    int lowest;
    int highest;
    float average;
    int range;
    int middle;
    double median;

    printf("\nEnter the amount of numbers you want?\n");
    scanf("%d",&n);

    int numbs[n];
    int temp[n];

    for(i = 0;i < n; i++)
    {
        printf("\nEnter a number from 0 to 15: ");
        scanf("%d",&temp[i]);
    }

    while (temp[i] < 0 || temp[i] > 15)  than 15
    {
        printf("This number is not from 0 to 15! Please re-enter another number: ");
        scanf("%d",&temp[i]);
    }

    numbs[i] = temp[i];
    sum += numbs[i];
}

int sortt = 0, j, x;

for (x = 1; x < n; x++) {
    for (j = 0; j < n - x; j++) {
        if (numbs[j] > numbs[j + 1]) {
            sortt = numbs[j];
            numbs[j] = numbs[j + 1];
            numbs[j + 1] = sortt;
        }
    }
}

lowest = numbs[0];
highest = numbs[n-1];
middle = n/2;

if (n % 2)
{
    median = numbs[middle];
}
else
{
    median = (numbs[middle - 1] + numbs[middle]) / 2.0;
}

average = sum/n;
range = highest - lowest;

printf("\nSum: %d", sum);
printf("\nAverage: %.2f", average);
printf("\nMedian: %.2f", median);
printf("\nRange: %d\n", range);

return 0;
}

这是我的输入和输出。你可以看到8除以3不是2,它是2.67!我尝试过使用double和float。

输入&amp;输出:

enter image description here

3 个答案:

答案 0 :(得分:1)

您需要更正以下行:

 average = sum/n;

 average = (float)sum/n;

您必须将返回值转换为float。将其视为具有以下定义的函数:

float divide(int x,int y){
     return x/y;  // returns an integer instead of float.
}

虽然这个定义:

float divide(int x,int y){
     return (float)x/y;  // creates a temporary float variable and returns it immediately as the returned value of the function.
}

此外,在使用int sum=0.0进行编译时,声明-Wall肯定会向您显示警告。尝试遵循从编译器获得的警告并在运行程序之前修复所有警告。

答案 1 :(得分:0)

8除以3是2,余数为2. 8和3是整数,当你除以两个整数时,你使用整数除法和整数规则。

此外,这一行可能让您感到困惑:

int sum = 0.0;

由于sumint,因此只需将sum设置为零。

average = sum/n;

由于sumn都是整数,因此这是整数除法。你对结果的处理并不影响计算结果的方式 - C的规则已经足够复杂了。

答案 2 :(得分:0)

/*Here see you can intake all values as float instead */ 
#include <stdio.h>
#include <stdlib.h>
 void main()
{
  float i,n,a,b,sum,ave;
  printf("This is a program to calculate the average of 'n' numbers \n");
  printf("Of How many numbers do you want to calculate average \n");
  scanf("%f", &n);
  printf("Enter the first number \n");
  scanf("%f", &a);
  sum = a;
    for (i=1;i<n;i++)
   {
    printf("Enter another number \n");
    scanf("%f", &b);
    sum = sum + b;
   }
   ave = (sum/n);
   printf("The average of the %f number is %f", n, ave);
   getchar();
}