编写一个函数 求n个数中的最大值 然后用c++语言表示出来。
时间: 2024-03-23 12:36:56 浏览: 17
好的,以下是求n个数中的最大值的C++代码:
```cpp
#include <iostream>
using namespace std;
int max(int arr[], int n) {
int max_num = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max_num) {
max_num = arr[i];
}
}
return max_num;
}
int main() {
int n;
cout << "请输入数的个数:";
cin >> n;
int arr[n];
cout << "请输入" << n << "个数:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int max_num = max(arr, n);
cout << "最大值为:" << max_num << endl;
return 0;
}
```
这段代码中,我们定义了一个求n个数中最大值的函数`max`,在`main`函数中,我们首先输入了数的个数和n个数,然后调用`max`函数求出最大值并输出。
相关问题
使用c++,编写一个能求编写一个能求两个或三个数中最大值的函数
好的,根据您的要求,我可以为您编写一个求两个或三个数中最大值的函数。请参考以下代码:
```c++
#include <iostream>
using namespace std;
int max(int a, int b) {
return (a > b) ? a : b;
}
int max(int a, int b, int c) {
return max(max(a, b), c);
}
int main() {
int a, b, c;
cout << "请输入两个或三个数,用空格隔开:";
cin >> a >> b >> c;
if (cin.fail()) {
cout << "输入无效!" << endl;
return 0;
}
if (c) {
cout << "最大值为:" << max(a, b, c) << endl;
} else {
cout << "最大值为:" << max(a, b) << endl;
}
return 0;
}
```
这个函数有两个版本:`max(int a, int b)` 可以求两个数的最大值,`max(int a, int b, int c)` 可以求三个数中的最大值。在主函数中,我们通过输入来确定要求几个数的最大值。运行程序时,您可以输入两个或三个数,程序会输出它们中的最大值。
用c++编写一个函数,输出3个数中最大数
以下是用C++编写的函数,可输出3个数中的最大数:
```cpp
#include <iostream>
using namespace std;
int max(int a, int b, int c){
int max = a;
if (b > max) {
max = b;
}
if (c > max) {
max = c;
}
return max;
}
int main(){
int a, b, c;
cout << "请输入三个整数:" << endl;
cin >> a >> b >> c;
cout << "最大数为:" << max(a, b, c) << endl;
return 0;
}
```
在上面的代码中,我们使用了一个 `max` 函数,该函数接收3个整数作为参数,并返回它们中的最大值。在 `main` 函数中,我们从控制台输入3个整数,并将它们传递给 `max` 函数,然后输出结果。