gpt4 book ai didi

c++ - 简单乘以 float 1000 * 0.01 = 9 的舍入错误

转载 作者:行者123 更新时间:2023-11-30 03:57:22 26 4
gpt4 key购买 nike

<分区>

使用 g++/visual studio 将 int 与 float 相乘将导致不正确的值

当使用 double 而不是 float 时,它总是可以正常工作。

计算也很简单 - 1000 * 0.01 - 应该是 10 - 但它是 9。

示例程序

#include <iostream>
#include <stdio.h>

typedef unsigned long long int64;
typedef unsigned int int32;

int main()
{
int64 test = 1000 * 0.01f;
printf("Test %u\n",test); // Prints 10

int64 test2 = 1000;
test2 = test2 * 0.01f;
printf("Test2 %u\n",test2); // Prints 9

int32 test3 = 1000;

test3 = test3 * 0.01f;
printf("Test3 %i\n",test3); // Prints 9

int64 test4 = 1000;
test4 = test4 * 0.01;
printf("Test4 %u\n",test4); // Prints 10

int32 test5 = 1000;

test5 = test5 * 0.01;
printf("Test5 %i\n",test5); // Prints 10

}

输出

Test 10
Test2 9
Test3 9
Test4 10
Test5 10

使用 g++ main.cpp -o main 在 Wheezy 32 位上编译

编辑:这只是过于简单化了!!!

基本上我不使用 0.01f

我所做的是将一个单位转换为另一个单位,例如我的一个单位是 1:100 到另一个单位。另一种是 1:10 或 1:1000。

所以如果我想对 2 个不同的单位求和,我基本上计算 unit1/unit2 以获得正确的乘数。

在那种情况下它是 unit1 = 1000 unit2 = 10

所以 10/1000 = 0.01 * 1000 = 10

所以当我想将 1000 个 unit1 转换成 unit2 时,结果应该是 10,因为基本上 unit1 是 1000 个基数,而 unit2 是 10 个基数。

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