亲,求指教c++:利用函数重载编写三个分别求短整数、整数和双精度数绝对值的函数,要求有输入输出。

2025-01-08 00:15:30
推荐回答(2个)
回答1:

#include
using namespace std;

short fun(short a)
{
if (a<0)
a = 0 - 1;
return a;
}

int fun(int a)
{
if (a<0)
a = 0 - 1;
return a;
}

double fun(double a)
{
if (a<0)
a = 0 - 1;
return a;
}

int main()
{
short a;
int b;
double c;
cin >> a >> b >> c;
cout << fun(a) << " " << fun(b) << " " <}

回答2:

#include

template
T _abs(T t) { return t > 0 ? t : -t; }

int main(int, char*[])
{
short a; int b; double c;
std::cin >> a >> b >> c;
std::cout << _abs(a) << '\n' << _abs(b) << '\n' << _abs(c) << '\n';
return 0;
}