Write a function template that accepts an argument and returns itsabsolute value. The absolute value of a number is its value with nosign. For example, the absolute value of -5 is 5, and the absolutevalue of 2 is 2. Name the function absValue. Place thetemplate in a file named valuea.cpp along with amain that illustrates that the template works forparameters of type int and float.

Sample:
Your output should reflect the values you used for your test cases.
Absolute value of -3 = 3
Absolute value of 5 = 5
Absolute value of -4.5 = 4.5
Absolute value of 3.2 = 3.2

Respuesta :

Answer:

#include<iostream>

#include<math.h>

using namespace std;

//create the template  function

template<class TypeVar>  

TypeVar absValue(TypeVar a1){

   return fabs(a1);

}

//main function

int main(){

  //display

   cout<<"Absolute value of -3 is "<<absValue(-3)<<endl;

   cout<<"Absolute value of 5 is "<<absValue(5)<<endl;

   cout<<"Absolute value of -4.5 is "<<absValue(-4.5)<<endl;

   cout<<"Absolute value of 3.2 is "<<absValue(3.2)<<endl;

   return 0;

}

Explanation:

Create the template which can work with any type like int, float, double.

syntax of the template:

template<class identifier>

then, the identifier is used in place of type and it works in all types.

The template is used in the code for making our function works for a different type of data, not limited to a single type.

After that, create the function with type TypeVar which is an identifier for our template and declare the one parameter with the same type.

and then, it returns the absolute value. the function used to convert into an absolute value is fabs().

it takes one parameter and it can be int, float and double.

Then, create the main function for testing our function.

call the function with a pass by value in the argument and it prints the output on the screen.