问题描述】 要求写出函数模板,对于任意类型的变量,均可产生模板函数,求出两个变量中的最小值。 【输入形式】 输入数据有三行,分别为: 两个整数 两个浮点数 两个字符 【输出形式】 输出数据有三行,分别为: 两个整数的最小值 两个浮点数的最小值 两个字符中的最小值 【样例输入】 100 200 1.3 1.2 a b 【样例输出】 100 1.2 a
时间: 2024-01-06 18:04:56 浏览: 30
```cpp
#include <iostream>
using namespace std;
template <typename T>
T min(T a, T b) {
return a < b ? a : b;
}
int main() {
int a, b;
double c, d;
char e, f;
cin >> a >> b >> c >> d >> e >> f;
cout << min(a, b) << endl;
cout << min(c, d) << endl;
cout << min(e, f) << endl;
return 0;
}
```
相关问题
要求写出函数模板,对于任意类型的变量,均可产生模板函数,求出两个变量中的最小值
下面是一个求取两个变量最小值的函数模板:
```cpp
template<typename T>
T min(T a, T b) {
return a < b ? a : b;
}
```
使用时,可以传入任意类型的参数:
```cpp
int a = 10, b = 20;
double c = 3.14, d = 2.718;
cout << min(a, b) << endl; // 输出 10
cout << min(c, d) << endl; // 输出 2.718
```
【平时考核】求两个变量中最小的那一个 【问题描述】 要求写出函数模板,对于任意类型的变量,均可产生模板函数,求出两个变量中的最小值。 【输入形式】 输入数据有三行,分别为: 两个整数 两个浮点数 两个字符
以下是求两个变量中最小的那一个的函数模板实现:
```cpp
#include <iostream>
using namespace std;
template <typename T>
T min(T a, T b) {
return a < b ? a : b;
}
int main() {
int a, b;
float c, d;
char e, f;
cin >> a >> b >> c >> d >> e >> f;
cout << "min of a and b: " << min(a, b) << endl;
cout << "min of c and d: " << min(c, d) << endl;
cout << "min of e and f: " << min(e, f) << endl;
return 0;
}
```
上述代码中的 `min()` 函数是一个模板函数,可以接受任意类型的参数。在 `main()` 函数中,我们分别输入了两个整数、两个浮点数和两个字符,并使用 `min()` 函数求出了它们中的最小值。
相关推荐
![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)