C ++:abs有什么问题

时间:2015-03-19 03:13:27

标签: c++

经过很长时间的程序追踪,我终于发现abs是我程序的可归责部分。我应该从这段代码中得到什么?为什么我会得到:

  

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;
}

2 个答案:

答案 0 :(得分:6)

您可能想知道“但为什么我没有在g++ -g -Wall -Wfatal-errors -Wextra -std=c++11 test.cpp -o ./bin/test -lboost_filesystem -lboost_system上收到警告?”

Turns out Wall isn't quite "all".

 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的诊断仍然更清晰,并且不需要明确的选择:

$ 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.

答案 1 :(得分:2)

您正在使用abs defined in <cstdlib>,它仅适用于整数。

请改用abs defined in <cmath>。它适用于浮点值。