iT邦幫忙

0

C++ fixed setprecision問題

#include < iostream >
#include < iomanip >
using namespace std;

double tryyy(double a){
double d=a+2-2;
return d;
}

int main(){

double n=-0.005;
cout<<fixed<<setprecision(2)<<n<<endl; //輸出-0.01
double s=tryyy(-0.005);
cout<<fixed<<setprecision(3)<<s<<endl; //輸出-0.005
cout<<fixed<<setprecision(2)<<s<<endl; //輸出-0.00

return 0;}

為什麼輸出的第三行(-0.00)會跟第一行(-0.01)是不一樣的呢?
我希望輸出的第三行,也就是取小數點後兩位之後也會是-0.01要怎麼做呢?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
richardsuma
iT邦大師 1 級 ‧ 2020-10-30 22:44:19
最佳解答

cout << fixed << setprecision(2) << round(s * 1000) / 1000 << endl;

感恩如此迅速地回答

我要發表回答

立即登入回答