平均值程序怎么写

时间:2025-01-26 21:46:43 单机游戏

求平均值的程序可以根据不同的编程语言和需求有多种实现方式。以下是几种常见编程语言的平均值计算示例:

Python 示例代码

```python

初始化变量

total = 0

count = 0

输入数据

while True:

num = input("请输入一个数字(输入q结束):")

if num == 'q':

break

else:

累加求和

total += float(num)

计数

count += 1

计算平均值

average = total / count

输出结果

print("平均值为:", average)

```

C 语言示例代码

示例 1

```c

include

int main() {

int n, i;

double a, sum = 0;

printf("输入 n: ");

scanf("%d", &n);

printf("输入 %d 个整数: ", n);

for(i = 1; i <= n; i++) {

scanf("%lf", &a[i]);

sum += a[i];

}

double average = sum / n;

printf("平均值为: %.2lf\n", average);

return 0;

}

```

示例 2

```c

include

int main() {

float average;

int i, x, sum = 0;

for(i = 1; i <= 5; i++) {

printf("number %d = ", i);

scanf("%d", &x);

sum += x;

}

average = sum / 5.0;

printf("average = %.2f\n", average);

return 0;

}

```

示例 3

```c

include

define N 5

int main() {

float average;

int i, x, sum = 0;

for(i = 1; i <= N; i++) {

printf("number %d = ", i);

scanf("%d", &x);

sum += x;

}

average = (float)sum / N;

printf("average = %.2f\n", average);

return 0;

}

```

示例 4

```c

include

include

int main() {

int one, two, three;

double four;

printf("请输入三个数值,无所谓正数还是负数 \n");

scanf("%d %d %d", &one, &two, &three);

four = (abs(one) + abs(two) + abs(three)) / 3.0;

printf("平均值为: %.2lf\n", four);

return 0;

}

```

示例 5

```c

include

int main() {

float mean;

int sum, i;

int n = 5;

int a[] = {2, 6, 7, 4, 9};

sum = 0;

for(i = 0; i < n; i++) {

sum += a[i];

}

printf("Mean = %f\n", sum / (float)n);

return 0;

}

```

示例 6

```c

include

int main() {

int n, i;

float num, sum = 0.0, average;

printf("请输入数字的个数: ");

scanf("%d", &n);

for (i = 0; i < n; ++i) {

printf("请输入数字%d: ", i + 1);

scanf("%f", &num);

sum += num;

}

average = sum / n;

printf("平均值 = %.2f\n", average);

return 0;

}

```

示例 7