c语言求各科平均分怎么编程

时间:2025-01-28 12:31:52 网络游戏

在C语言中,求各科平均分可以通过以下几种方法实现:

方法一:使用数组

```c

include

include

include

struct student {

int score;

};

int average(int *p) {

return (*p + *(p + 1) + *(p + 2)) / 3;

}

int main() {

srand(time(NULL));

struct student stu1, stu2, stu3, stu4;

int result1, result2, result3, result4;

for (int k = 1; k <= 3; k++) {

stu1.score[k] = rand() % 100;

stu2.score[k] = rand() % 100;

stu3.score[k] = rand() % 100;

stu4.score[k] = rand() % 100;

}

result1 = average(stu1.score);

result2 = average(stu2.score);

result3 = average(stu3.score);

result4 = average(stu4.score);

printf("学生1的平均分: %d\n", result1);

printf("学生2的平均分: %d\n", result2);

printf("学生3的平均分: %d\n", result3);

printf("学生4的平均分: %d\n", result4);

return 0;

}

```

方法二:使用指针和函数

```c

include

void average(float *p, int n) {

float sum = 0, aver;

float *p_end = p + n - 1;

for (; p <= p_end; p++) {

sum += *p;

}

aver = sum / n;

printf("平均分: %.2f\n", aver);

}

int main() {

float scores = {

{87, 72, 93},

{90, 85, 78},

{75, 80, 95},

{88, 92, 76}

};

for (int i = 0; i < 4; i++) {

average(scores[i], 3);

}

return 0;

}

```

方法三:使用标准输入输出

```c

include

int main() {

int score1, score2, score3;

printf("请输入三个学生的成绩:\n");

scanf("%d%d%d", &score1, &score2, &score3);

float average = (score1 + score2 + score3) / 3.0;

printf("三个学生的平均分为:%.2f\n", average);

return 0;

}

```

方法四:使用数组和循环

```c

include

int main() {

int scores = {

{87, 72, 93},

{90, 85, 78},

{75, 80, 95},

{88, 92, 76},

{95, 89, 77},

{82, 79, 91},

{78, 83, 94},

{92, 87, 79},

{85, 90, 80},

{90, 88, 82}

};

int sum, average;

int i, n = 10;

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

sum = scores[i] + scores[i] + scores[i];

average = sum / 3;

printf("学生%d的平均分: %.2f\n", i + 1, average);

}

return 0;

}

```

这些方法展示了如何在C语言中计算多个学生的各科平均分。