C ++: what's wrong with abs

After a long trace of my program, I finally discovered what abswas the guilty part of my program. What should I expect from this code? why 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;
}
+4
source share
2 answers

You use abs, defined in<cstdlib> , which only works with integers.

Use defined in . It works with floating point values. abs<cmath>

+2
source

You might be wondering: "But why didn't I get a warning on g++ -g -Wall -Wfatal-errors -Wextra -std=c++11 test.cpp -o ./bin/test -lboost_filesystem -lboost_system?"

Turns off is Wallnot quite "everything."

 g++ -g -Wconversion -std=c++11 test.cpp -o tester -lboost_filesystem -lboost_system
test.cpp: In function ‘int main()’:
test.cpp:7:29: warning: conversion to ‘int’ from ‘double’ may alter its value [-Wconversion]
     std::cout<<"|x|="<<abs(x)<<std::endl;
                             ^

clang-3.6 the diagnosis is even clearer and no explicit rejection is required:

$ clang++ -std=c++11 test.cpp -o tester
test.cpp:8:24: warning: using integer absolute value function 'abs' when argument is of floating point type [-Wabsolute-value]
    std::cout<<"|x|="<<abs(x)<<std::endl;
                       ^
test.cpp:8:24: note: use function 'std::abs' instead
    std::cout<<"|x|="<<abs(x)<<std::endl;
                       ^~~
                       std::abs
test.cpp:8:24: note: include the header <cmath> or explicitly provide a declaration for 'std::abs'
1 warning generated.
+5

All Articles