c++ - C++ 中的固定和设置精度

标签 c++ c++11

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

int main()
{
    float c = 5.0;
    float far = (9/5)*c + 32;
    cout << fixed << "Temperature in Fahrenheit is "<< setprecision(2) << 
    far;
    return 0;
} 

我预计输出为 41.00,但实际输出为 37.00。

最佳答案

请注意,95int,因此 9/5 结果为 int 1.

您的代码在 float 上运行,并且需要 float 乘数才能使转换正常工作。因此,解决方法是将乘数定义为 9.f/5 (..0 指数的简写符号, f 后缀指定一个 float 文字,请参阅 floating point literal 了解更多详细信息),例如:

float far = (9.f / 5) * c + 32;

关于c++ - C++ 中的固定和设置精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57713990/

相关文章:

c++ - 关于weak_ptr的线程安全

c++ - 如何将写入缓冲区添加到io.h中定义的写入中

c++ - 后增量运算符如何与用户定义的类型一起使用?

c++ - 整数序列实现 C++

c++ - GDB:运行没有符号的cpp进程调试

android - 我的 native C++ Android 程序中缺少 glShaderModel 库

c++ - 当 vector 增长时如何强制执行 move 语义?

c++ - 返回类型推导

c++ - TMP : how to write template code which converts any struct into a tuple?

c++ - c++11 中的关键字 typeof