以下是 C 语言程序实现对一维数组的基本操作的示例:
输入:
#include <stdio.h>
#define N 10
int main(void) {
int a[N];
printf("请输入 %d 个整数:\n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
return 0;
}
输出:
#include <stdio.h>
#define N 10
int main(void) {
int a[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printf("数组 a 中的元素为:\n");
for (int i = 0; i < N; i++) {
printf("%d ", a[i]);
}
return 0;
}
求平均值:
#include <stdio.h>
#define N 10
int main(void) {
int a[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i = 0; i < N; i++) {
sum += a[i];
}
printf("数组 a 的平均值为:%.2f\n", (double)sum / N);
return 0;
}
求最大值:
#include <stdio.h>
#define N 10
int main(void) {
int a[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int max = a[0];
for (int i = 1; i < N; i++) {
if (a[i] > max) {
max = a[i];
}
}
printf("数组 a 中的最大值为:%d\n", max);
return 0;
}
排序:
“` #include <stdio.h>
#define N 10
int main(void) { int a[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int i = 0; i < N – 1; i++) { for (int j = 0; j < N – i – 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] =
版权声明:本文为weixin_35757531原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。