You are to find all the absolute value functions you can and rewrite all of them
ID: 3731759 • Letter: Y
Question
You are to find all the absolute value functions you can and rewrite all of them overloading the abs function name. At a minimum, you should have the int, long, float, and double types represented.
Variables:
Declare four variables of type int, double, float, long and initialize them to some random values:
int i = -4;
double d = 7.5;
Functions:
Call your functions Abs( )
From main, call the four overloaded functions with these variables.
In each function, place a debug statement to print out which function is being called. For example:
cout<<"Abs(int) is being called"<<endl;
Place appropriate cout functions in main to let the user know what is being called, how it's being called and what the result it.
Explanation / Answer
#include<iostream>
using namespace std;
int abs(int n)
{
cout<<"Abs(int) is being called : ";
// if n is negative
if( n < 0 )
return -n;
else
return n;
}
double abs(double n)
{
cout<<"Abs(double) is being called : ";
// if n is negative
if( n < 0 )
return -n;
else
return n;
}
float abs(float n)
{
cout<<"Abs(float) is being called : ";
// if n is negative
if( n < 0 )
return -n;
else
return n;
}
long abs(long n)
{
cout<<"Abs(long ) is being called : ";
// if n is negative
if( n < 0 )
return -n;
else
return n;
}
int main()
{
int a = -3;
float b = -3.25;
double c = -4.56;
long d = 2;
cout<<abs(a)<<endl;
cout<<abs(b)<<endl;
cout<<abs(c)<<endl;
cout<<abs(d)<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.