gpt4 book ai didi

C++:abs有什么问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:22:56 29 4
gpt4 key购买 nike

经过长时间跟踪我的程序,我终于发现 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 上收到警告?”

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.

关于C++:abs有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29136607/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com