C++:腹肌怎么了

C++: what is wrong with abs

本文关键字:怎么了 C++      更新时间:2023-10-16

经过长时间的程序跟踪,我终于发现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;
}

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

事实证明Wall并不是"全部"。

 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.

您使用的是<cstdlib>中定义的abs,它只适用于整数。

请改用<cmath>中定义的abs。它适用于浮点值。