problems with cmath overloaded functions C++

风流意气都作罢 提交于 2019-12-11 03:02:28

问题


I need to use cmath's abs() function, but Visual Studio says it's overloaded and I can't even use something like this:

unsigned a = 5, b = 10, c;
c = abs(a-b);

I don't know how to use it properly.


回答1:


The versions in <cmath> are for floating point types, so there is no unambiguously best match. The overload for integral types are in <cstdlib>, so one of those will yield a good match. If you are using abs on different types, you can use both includes and let overload resolution do its work.

#include <cmath>
#include <cstdlib>
#include <iostream>

int main()
{
  unsigned int a = 5, b = 10, c;
  c = std::abs(a-b);      
  std::cout << c << "\n"; // Ooops! Probably not what we expected.
}

On the other hand, this doesn't yield correct code, since the expression a-b does not invoke integer promotion, so the result is an unsigned int. The real solution is to use signed integral types for differences, as well as the integral type std::abs overloads.




回答2:


As you can see here, there is no cmath function abs that takes an unsigned integer. This is because unsigned integers are never negative. Try doing the following instead:

int a = 5, b = 10;
int c = abs(a-b);

In this case, c = 5 as expected.




回答3:


You can use the ternary operator:

c = (a > b) ? a - b : b - a;


来源:https://stackoverflow.com/questions/15217936/problems-with-cmath-overloaded-functions-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!