I was wondering if what I have done is correct or not. Here's what my book says to do:

"Write a function template that accepts an argument and returns its absolute value. The absolute value of a number is its value with no sign. For example, the absolute value of -5 is 5, and the absolute value of 2 is 2. Test the template in a simple driver program."

This is the code that I've done:

// This program displays the absolute value of an entered number.
#include <iostream>
#include <cmath>
#include <conio>
using namespace std;

template <class T>
T abs(T val1)
	return val1;

int main()
        double num1;

	cout << "Enter a number, and I will display the absolute value of that number: ";
	cin >> num1;
	cout << "The absolute value of the enterend number is: " << abs(num1) << endl;

	return 0;
9 Years
Discussion Span
Last Post by Laiq Ahmed

what about the following code.

template<class T> 
T const& Absolute(T const& v)
	if (v < 0)
		return (v + (-v*2));
	return v;

requires minute mathematics.


Yeah, so basically if you put a number that is a decimal, then it'll truncate the rest after the decimal place, therefore making it an integer. Correct?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.