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
Numerical Recipes 3rd Edition
William H. Press、Saul A. Teukolsky、William T. Vetterling、Brian P. Flannery / Cambridge University Press / 2007-9-6 / GBP 64.99
Do you want easy access to the latest methods in scientific computing? This greatly expanded third edition of Numerical Recipes has it, with wider coverage than ever before, many new, expanded and upd......一起来看看 《Numerical Recipes 3rd Edition》 这本书的介绍吧!
JSON 在线解析
在线 JSON 格式化工具
html转js在线工具
html转js在线工具