If I enable double and integer only, then it is 4 functions. But I want to enable all data types (int long float double unsigned numbers etc.) How is it possible?
#include <iostream>
using namespace std;
double diff(int num1, int num2) {
return double(num1-num2);
}
double diff(int num1, double num2) {
return double(num1)-num2;
}
double diff(double num1, int num2) {
return num1-double(num2);
}
double diff(double num1, double num2) {
return num1-num2;
}
int main() {
int a = 10;
double b = 4.4;
cout << diff(a, b) << endl;
return 0;
}
Formula To Calculate Percentage Difference Between Two Numbers. result = ( abs(a-b) / ((a+b) / 2.0) ) * 100; Note: abs() is a builtin method present in stdlib. h header file, which returns the absolute value.
How to Find the Difference between Two Numbers. To find the difference between two numbers, subtract the number with the smallest value from the number with the largest value. The product of this sum is the difference between the two numbers.
difference = num1 - num2; We calculate the difference of two numbers using the Minus(-) operator. printf("Difference of %d and %d is: %d", num1, num2, difference); printf("Difference of %d and %d is: %d", num1, num2, difference);
template <typename T, typename U>
double diff(T a, U b) {
return a - b;
}
You don't need the cast to double
-- this is done for you if either argument is a double
, and during return
when both are integers. However,
double diff(double a, double b);
can be called with int
arguments as well.
Use a template function:
template <typename T1, typename T2>
double diff(const T1& lhs, const T2& rhs)
{
return lhs - rhs;
}
You don't have to "enable" operations, just write:
cout << (a - b) << endl;
Unlike all of previous answers I would add about C++11. In C++11 you can use decltype
.
#include <iostream>
template <typename T1, typename T2>
auto diff(T1 a, T2 b) -> decltype(a)
{
return (a - b);
}
int main() {
std::cout << diff(3.5, 1) << std::endl;
std::cout << diff(3, 1.5) << std::endl;
}
diff
function will always return value of type like first argument. Note in first case it is float number, but in second it is integer.
You could define a template for the same
template <typename T, typename U>
T diff(const T& a, const U& b) {
return a - b;
}
This code makes a lot of assumptions, like operator - is defined for T, and return type will be always of type T and so on...
You could always calculate the difference using absolute values, for instance
cout << abs(a - b) << endl;
you might want to use templates like previous answers said though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With