用c++ 编写一个函数,求出两个整数中较大的一个。
时间: 2024-02-25 15:53:33 浏览: 25
可以用下面的代码来实现:
```c++
#include<iostream>
using namespace std;
int max(int a, int b) {
return a > b ? a : b;
}
int main() {
int a = 5, b = 10;
cout << "The bigger number is " << max(a, b) << endl;
return 0;
}
```
这个程序中,我们定义了一个返回两个整数中较大值的函数 `max`,然后在 `main` 函数中调用它并输出结果。输出结果为:
```
The bigger number is 10
```
相关问题
使用C++ 编写三个函数,分别求两个整数、两个浮点数、两个 字符中较大的那一个,并在主函数中调用测试。
以下是使用 C++ 编写的三个函数,用于比较两个整数、两个浮点数和两个字符中较大的那一个:
```cpp
#include <iostream>
using namespace std;
// 比较两个整数中较大的那一个
int max(int a, int b) {
return (a > b) ? a : b;
}
// 比较两个浮点数中较大的那一个
float max(float a, float b) {
return (a > b) ? a : b;
}
// 比较两个字符中较大的那一个
char max(char a, char b) {
return (a > b) ? a : b;
}
int main() {
int a1 = 10, b1 = 20;
float a2 = 3.14, b2 = 2.71;
char a3 = 'A', b3 = 'B';
cout << "Max of " << a1 << " and " << b1 << " is " << max(a1, b1) << endl;
cout << "Max of " << a2 << " and " << b2 << " is " << max(a2, b2) << endl;
cout << "Max of " << a3 << " and " << b3 << " is " << max(a3, b3) << endl;
return 0;
}
```
输出结果为:
```
Max of 10 and 20 is 20
Max of 3.14 and 2.71 is 3.14
Max of A and B is B
```
用C++编写三个函数,分别求两个整数、两个浮点数、两个字符中较大的哪一个,并在主函数中调用测试
以下是用C++编写的三个函数,分别求两个整数、两个浮点数、两个字符中较大的哪一个:
```c++
#include <iostream>
using namespace std;
int max(int a, int b) {
return a > b ? a : b;
}
float max(float a, float b) {
return a > b ? a : b;
}
char max(char a, char b) {
return a > b ? a : b;
}
int main() {
int i1 = 10, i2 = 20;
float f1 = 3.14, f2 = 2.71;
char c1 = 'A', c2 = 'a';
cout << "Max of " << i1 << " and " << i2 << " is " << max(i1, i2) << endl;
cout << "Max of " << f1 << " and " << f2 << " is " << max(f1, f2) << endl;
cout << "Max of " << c1 << " and " << c2 << " is " << max(c1, c2) << endl;
return 0;
}
```
输出结果如下:
```
Max of 10 and 20 is 20
Max of 3.14 and 2.71 is 3.14
Max of A and a is a
```