C++实现在主函数中输入某班同学的成绩,并调用函数求出全班同学的成绩之和和平均分
时间: 2024-06-06 12:08:14 浏览: 12
#include <stdio.h>
#define SIZE 10 // 假设班级人数为10人
// 声明函数
void calculate(int array[], int size, int *sum, double *average);
int main() {
int scores[SIZE];
int sum = 0;
double average = 0.0;
// 输入成绩
printf("请输入%d个同学的成绩:\n", SIZE);
for (int i = 0; i < SIZE; i++) {
scanf("%d", &scores[i]);
}
// 计算总分和平均分
calculate(scores, SIZE, &sum, &average);
// 输出结果
printf("全班同学的成绩之和为:%d,平均分为:%.2lf\n", sum, average);
return 0;
}
// 定义函数
void calculate(int array[], int size, int *sum, double *average) {
*sum = 0;
for (int i = 0; i < size; i++) {
*sum += array[i];
}
*average = (double)*sum / size;
}
相关问题
C++声明一个Student类,在该类中包括一个数据成员实现在主函数中输入某班同学的成绩,并调用函数求出全班同学的成绩之和和平均分
```
#include <iostream>
using namespace std;
class Student {
public:
int score;
};
int main() {
int n;
cout << "请输入班级人数:";
cin >> n;
Student* students = new Student[n];
int sum = 0;
for (int i = 0; i < n; i++) {
cout << "请输入第" << i + 1 << "个同学的成绩:";
cin >> students[i].score;
sum += students[i].score;
}
cout << "全班同学的成绩之和为:" << sum << endl;
cout << "全班同学的平均分为:" << sum / n << endl;
delete[] students;
return 0;
}
```
在主函数中输入两个正整数,调用函数求它们的最小公倍数,结果在主函数中输出。
好的,这是一个比较简单的数学问题。以下是用 C++ 实现的代码:
```cpp
#include <iostream>
using namespace std;
// 定义函数求两个数的最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// 定义函数求两个数的最小公倍数
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int main() {
int num1, num2;
cout << "请输入两个正整数:" << endl;
cin >> num1 >> num2;
cout << "它们的最小公倍数为:" << lcm(num1, num2) << endl;
return 0;
}
```
在这个程序中,我们首先定义了求两个数的最大公约数的函数 `gcd`,然后再用最大公约数求出最小公倍数的函数 `lcm`。在主函数中,我们先输入两个正整数,然后调用 `lcm` 函数求出它们的最小公倍数,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)