gpt4 book ai didi

c++ - 为什么 1.0 乘以 5 得到输出 5 而不是 5.0?

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

cout<<5*1.0<<endl;
cout<<(float)5<<endl;

在这两种情况下,我的答案都是 5 而不是 5.0。请帮助...

最佳答案

需要指定floatingPoint输出的格式和精度,如:

std::cout << std::fixed << std::setprecision(1) << 5*1.0;

LIVE

来自 [The.C++.Programming.Language.Special.Edition] 21.4.3 浮点输出 [io.out.float]:

Floatingpoint output is controlled by a format and a precision:

– Thegeneral format lets the implementation choose a format that presents avalue in the style that best preserves the value in the spaceavailable. The precision specifies the maximum number of digits. Itcorresponds to printf()’s %g (§21.8).

– The scientific format presentsa value with one digit before a decimal point and an exponent. Theprecision specifies the maximum number of digits after the decimalpoint. It corresponds to printf()’s %e .

– The fixed format presents avalue as an integer part followed by a decimal point and a fractionalpart. The precision specifies the maximum number of digits after thedecimal point. It corresponds to printf()’s %f .

关于c++ - 为什么 1.0 乘以 5 得到输出 5 而不是 5.0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31018436/

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