小编W.Z*_*Hai的帖子

为什么在C++中这个double值乘以2会出现计算错误?

#include <iostream>
#include <stdint.h>
#include <bitset>
#include <sstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
    uint64_t int_value = 0b0000000000001101000011110100001011000000110111111010111101110011;
    double double_value = (*((double *)((void *)&int_value)));
    printf("double initiate value: %e\n", double_value);
    cout << "sign " << setw(11) << "exp"
         << " " << setw(52) << "frac" << endl;
    for (int i = 0; i < 10; i++)
    {
        stringstream ss;
        ss << bitset<64>((*((uint64_t *)((void *)&double_value))));
        auto str = ss.str();
        cout << setw(4) << str.substr(0, 1) << " " …
Run Code Online (Sandbox Code Playgroud)

c++ ieee-754 calculation

4
推荐指数
1
解决办法
93
查看次数

为什么带有 %.2g 的 printf 在点后不显示两位数字?

#include <stdio.h>

int main()
{
    printf("%.2g %.2f\n", 2.925, 2.925);
}
Run Code Online (Sandbox Code Playgroud)

我认为正确的输出应该是:

2.93 2.93
Run Code Online (Sandbox Code Playgroud)

现在,输出如下:

2.9 2.92
Run Code Online (Sandbox Code Playgroud)

有两个误解:

  1. 为什么 '%.2g' 不显示点后的两位数?

  2. 为什么四舍五入?

c floating-point

3
推荐指数
1
解决办法
62
查看次数

标签 统计

c ×1

c++ ×1

calculation ×1

floating-point ×1

ieee-754 ×1