编写函数,对int、double和float类型数据求绝对值,采用函数重载的形式实现
时间: 2024-05-04 14:15:46 浏览: 22
好的,以下是实现这个要求的函数重载:
```
#include <iostream>
using namespace std;
// 求int类型数据的绝对值
int abs(int num) {
return num < 0 ? -num : num;
}
// 求float类型数据的绝对值
float abs(float num) {
return num < 0 ? -num : num;
}
// 求double类型数据的绝对值
double abs(double num) {
return num < 0 ? -num : num;
}
// 测试
int main() {
int i = -10;
float f = -2.5;
double d = -33.8;
cout << abs(i) << endl;
cout << abs(f) << endl;
cout << abs(d) << endl;
return 0;
}
```
如果您有任何问题,可以随时问我!
相关问题
编写函数,对int、double和float类型数据求绝对值,采用函数重载的形式实现。
好的,这个问题我可以直接回答。以下是重载的函数代码示例:
```
#include <iostream>
#include <cmath>
using namespace std;
int abs(int a){
return abs(a);
}
double abs(double a){
return abs(a);
}
float abs(float a){
return abs(a);
}
int main(){
int a = -1;
double b = -3.14;
float c = 2.5f;
cout << abs(a) << endl;
cout << abs(b) << endl;
cout << abs(c) << endl;
return 0;
}
```
使用 `abs()` 函数可以求出各种类型数据的绝对值,包括 int、double和float类型数据。
利用函数重载编写求整数绝对值和求实数绝对值两个函数
函数重载是指在同一个作用域内,可以定义多个名称相同但参数列表不同的函数。利用函数重载,我们可以编写求整数绝对值和求实数绝对值两个函数。在引用的代码中,我们定义了一个名为jued的类,其中包含了两个函数jued1,一个用于求整数绝对值,一个用于求实数绝对值。当传入的参数为整数时,调用第一个jued1函数,当传入的参数为实数时,调用第二个jued1函数。在函数内部,我们使用if语句判断参数是否小于0,如果小于0,则将其乘以-1,即取其绝对值。最后,函数返回绝对值并输出数据类型。在main函数中,我们创建了一个jued类的对象a,并分别调用了四次jued1函数,输出了整数和实数的绝对值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)