c++std

Why is my C++ abs function returning an int?


After a long time trace of my program I finally found that abs is the blameable part of my program. What should I expect from this code? why do I get:

x=0.1

|x|=0

#include <iostream>

int main()
{
    double x=0.1;
    std::cout<<"x="<<x<<std::endl;
    std::cout<<"|x|="<<abs(x)<<std::endl;
    return 0;
}

Solution

  • You're using the abs defined in <cstdlib>, which only works on integers.

    Use the abs defined in <cmath> instead. It works on floating point values.