计算数组中整数的平均值

时间:2019-08-03 15:15:37

标签: c arrays average

我必须计算数组内部整数的平均值:

int main(void)
{
    int num;
    printf("How many elements do you want to add in to the array? --> ");
    scanf("%d", &num);
    float array[10];
    float total, average;

    for(int i=0; i<num; i++){
        printf("Insert the element: ");
        scanf("%f", &array[i]);
        total = total + array[i];
    }

    average = total/num;
    printf("The average is: %.2f\n", total);

    return 0;
}

输出:

How many elements do you want to add in to the array?  --> 3
Insert the element: 5
Insert the element: 6
Insert the element: 7
The average is: 18.00

我希望输出为6.00,但它为18.00。我该如何解决?

1 个答案:

答案 0 :(得分:0)

#include<stdio.h>
int main()
{
    float avg,sum=0;
    int i;
    float marks[3];//array declaration
    for(i=0;i<=2;i++)
    {
        printf("enter marks\n");
        scanf("%f",&marks[i]); //store data in array
        printf("you have entered %f\n",marks[i]);
        sum=sum+marks[i];
    }
    printf("\nou have entered sum=%f\n",sum);
    avg=sum/3;
    printf("average marks=%f\n",avg);
    return 0;
}