C 语言实例 - 计算数组元素平均值

C 语言教程 · 2019-02-20 23:26:33

使用 for 循环迭代出输出元素,并将各个元素相加算出总和,再除于元素个数:

实例 1

#include <stdio.h> int main() { int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0}; int sum, loop; float avg; sum = avg = 0; for(loop = 0; loop < 10; loop++) { sum = sum + array[loop]; } avg = (float)sum / loop; printf("平均值为 %.2f", avg); return 0; }

输出结果为:

平均值为 4.50

用户自定义输入:

实例 2

#include <stdio.h> int main() { int n, i; float num[100], sum = 0.0, average; printf("输入元素个数: "); scanf("%d", &n); while (n > 100 || n <= 0) { printf("Error! 数字需要在1 到 100 之间。\n"); printf("再次输入: "); scanf("%d", &n); } for(i = 0; i < n; ++i) { printf("%d. 输入数字: ", i+1); scanf("%f", &num[i]); sum += num[i]; } average = sum / n; printf("平均值 = %.2f", average); return 0; }

输出结果为:

输入元素个数: 4
1. 输入数字: 1
2. 输入数字: 2
3. 输入数字: 4
4. 输入数字: 8
平均值 = 3.75

点击查看所有 C 语言教程 文章: https://codercto.com/courses/l/17.html

查看所有标签

Foundations of PEAR

Foundations of PEAR

Good, Nathan A./ Kent, Allan / Springer-Verlag New York Inc / 2006-11 / $ 50.84

PEAR, the PHP Extension and Application Repository, is a bountiful resource for any PHP developer. Within its confines lie the tools that you need to do your job more quickly and efficiently. You need......一起来看看 《Foundations of PEAR》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

URL 编码/解码
URL 编码/解码

URL 编码/解码