c++实现4个数取最大值
时间: 2023-11-24 12:43:23 浏览: 38
您可以使用以下C++代码来实现4个数的最大值:
```cpp
#include <iostream>
int getMax(int a, int b, int c, int d) {
int max = a;
if (b > max)
max = b;
if (c > max)
max = c;
if (d > max)
max = d;
return max;
}
int main() {
int num1, num2, num3, num4;
std::cout << "请输入四个数:" << std::endl;
std::cin >> num1 >> num2 >> num3 >> num4;
int maxNum = getMax(num1, num2, num3, num4);
std::cout << "最大值是:" << maxNum << std::endl;
return 0;
}
```
在这个示例中,我们定义了一个名为`getMax`的函数,它接受四个整数参数并返回这四个数中的最大值。然后在`main`函数中,我们从用户输入获取四个数,并调用`getMax`函数来获取最大值,并将最大值输出到控制台上。
相关问题
用C++编写一个程序完成下列题目,利用函数模板实现三个数取最大值和最小值功能,要求支持 int、float、double。
好的,以下是实现这个功能的 C++ 代码:
```cpp
#include <iostream>
#include <algorithm>
template<typename T>
T getMax(T a, T b, T c) {
return std::max(std::max(a, b), c);
}
template<typename T>
T getMin(T a, T b, T c) {
return std::min(std::min(a, b), c);
}
int main() {
int a = 1, b = 2, c = 3;
float d = 1.1, e = 2.2, f = 3.3;
double g = 1.11, h = 2.22, i = 3.33;
std::cout << "Max of int: " << getMax(a, b, c) << std::endl;
std::cout << "Max of float: " << getMax(d, e, f) << std::endl;
std::cout << "Max of double: " << getMax(g, h, i) << std::endl;
std::cout << "Min of int: " << getMin(a, b, c) << std::endl;
std::cout << "Min of float: " << getMin(d, e, f) << std::endl;
std::cout << "Min of double: " << getMin(g, h, i) << std::endl;
return 0;
}
```
我们定义了两个函数模板:`getMax` 和 `getMin`,用于分别获取三个数中的最大值和最小值。这两个函数模板都接受三个参数,类型为 `T`,即可以是 `int`、`float`、`double` 中的任意一种。
在 `main` 函数中,我们分别定义了三个 `int`、`float`、`double` 类型的变量,并分别调用了 `getMax` 和 `getMin` 函数模板,输出了结果。
这个程序可以输出以下结果:
```
Max of int: 3
Max of float: 3.3
Max of double: 3.33
Min of int: 1
Min of float: 1.1
Min of double: 1.11
```
多线程环境取最大值代码实现
下面是一个使用互斥锁实现在多线程环境下取最大值的代码示例(使用 C++11 标准的 std::mutex):
```c++
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
std::mutex mtx; // 定义互斥锁
void find_max(const std::vector<int>& nums, int& max_num)
{
for (auto num : nums) {
mtx.lock(); // 获取互斥锁
if (num > max_num) {
max_num = num;
}
mtx.unlock(); // 释放互斥锁
}
}
int main()
{
std::vector<int> nums = {2, 5, 8, 1, 9, 4};
int max_num = 0;
// 启动两个线程分别查找最大值
std::thread t1(find_max, std::ref(nums), std::ref(max_num));
std::thread t2(find_max, std::ref(nums), std::ref(max_num));
// 等待两个线程结束
t1.join();
t2.join();
std::cout << "The max number is: " << max_num << std::endl;
return 0;
}
```
在上面的代码中,我们定义了一个互斥锁 `mtx`,然后在查找最大值的函数中先获取互斥锁,然后进行比较和更新最大值,最后再释放互斥锁。这样可以确保在任意时刻只有一个线程能够修改最大值,避免了多线程竞争导致的数据不一致问题。