Home >Backend Development >C#.Net Tutorial >How to find the average of n numbers in C language?

How to find the average of n numbers in C language?

尚
Original
2020-03-05 13:24:0729931browse

How to find the average of n numbers in C language?

C language to find the average of n numbers:

Recommended: "c Language Tutorial"

#include<stdio.h>
int main(void)
{
int a[100] = { NULL };//初始化数组元素
int i = 0, n;//定义循环变量和正整数变量n
float sum = 0.0;//定义和变量为float型,注意计算的数据类型
float average = 0.0;//定义平均数变量为float型,注意计算的数据类型
printf("Please input n (n<100) :");
scanf("%d", &n);//输入正整数n
printf("Please input %d integers:", n);//提示输入几个正整数
for (i = 0; i < n; i++)//循环输入元素
{
scanf("%d", &a[i]);//输入整形变量
sum += a[i];//循环输入的时候同时进行求和
}
//for (i = n - 1; i >= 0; i--)
printf("the a[n] number: ");//倒叙输出数组元素
for (i = 0; i < n; i++)//循环输入元素
printf("%d ", a[i]);//倒叙输出数组元素
printf("\n");
average = sum / (float)n;//注意不同类型之间的计算,这里加了类型强制转换
printf("averge=%.2f\n", average);//输出平均数
return 0;
}

The program running results are as follows:

How to find the average of n numbers in C language?

For more programming-related content, please pay attention to the Programming Introduction column on the php Chinese website!

The above is the detailed content of How to find the average of n numbers in C language?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn