简体   繁体   English

如何计算c ++中两个数字的差异?

[英]How to calculate the difference of two numbers in c++?

If I enable double and integer only, then it is 4 functions. 如果我只启用double和integer,那么它是4个函数。 But I want to enable all data types (int long float double unsigned numbers etc.) How is it possible? 但我想启用所有数据类型(int long float double unsigned numbers等)。它怎么可能?

#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;
}
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. 你不需要使用强制转换double - 如果任一参数是double ,并且在return时两者都是整数,则会为你完成。 However, 然而,

double diff(double a, double b);

can be called with int arguments as well. 也可以使用int参数调用。

Use a template function: 使用模板功能:

template <typename T1, typename T2>
double diff(const T1& lhs, const T2& rhs)
{
  return lhs - rhs;
}

您不必“启用”操作,只需写:

cout << (a - b) << endl;

Unlike all of previous answers I would add about C++11. 与之前的所有答案不同,我将添加有关C ++ 11的内容。 In C++11 you can use decltype . 在C ++ 11中,您可以使用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. diff函数将始终返回类型的值,如第一个参数。 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... 这个代码做了很多假设,比如运算符 - 是为T定义的,返回类型总是T类型等等......

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. 你可能想要使用像之前的答案那样的模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM