问题与浮点重新presentation [英] Issue with Floating points representation

查看:119
本文介绍了问题与浮点重新presentation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请尝试以下code:

#include <stdio.h>

unsigned char TEST_COMPILER_AS13 = 1.18 * 100;

int main(void) {
    printf("%d" , TEST_COMPILER_AS13);
    // your code goes here
    return 0;
}

使用C


的https://www.$c$cchef.com/ide

结果将是117

如果我们换成1.18 1.17与该结果将是116,但如果我们用1.19,1.20,1.15等结果将是正确的119,120,115。

if we replaced 1.18 with 1.17 the result would be 116 , yet if we used 1.19,1.20,1.15 etc the result would be correct 119 , 120 , 115.

说: HTTP://$c$cpad.org/
为1.18和1.17,结果会好
但这时如果你尝试过1.13,1.14,1.15它会112,113,114分别为

using different online compiler say :http://codepad.org/ the results for 1.18 and 1.17 would be okey yet then if you tried 1.13 , 1.14 , 1.15 it would 112 , 113 , 114 respectively

我擦我的头,我不能明白为什么这种情况发生。
注意:
我曾尝试不同的编译器DIAB,COSMIC,MinGW的。等等
都有类似的问题。所以什么即时在这里失踪或浮点运算是如何完成的。

I'm rubbing my head and i cant understand why this happen. Note: I have tried different compilers DIAB, COSMIC , MinGw.. etc all have similar issue. so what im missing here or how the floating point operations are done.

请注意:
要解决这个问题,你可以只投的操作使用float
这样的声明将是如下

Note: to solve this issue you could just cast the operation with float so the declaration would be as follow

unsigned char TEST_COMPILER_AS13 = (float) (1.18 * 100);

我接受你的答案,我真的想了解如何工作的。为什么它适用于一些数字和其他惯于,为什么编译器在处理它的方式不同,有没有这会影响编译器行为编译器选项

I'm open to your answers , i really want to understand how this works. why it works for some number and others wont, Why compiler differs on the way to handle it , is there compiler options which would affect the compiler behaviour

推荐答案

你有它的方式,浮点值被截断为整数类型(无符号字符)。四舍五入到最接近的,而不是用这个。

The way you have it, the floating point value is truncated to an integer type (unsigned char). To round to nearest, use this instead.

unsigned char TEST_COMPILER_AS13 = 1.18 * 100 + 0.5;

虽然这可能对于这种情况下的修复它,总是会有浮点运算precision问题。见@JohnnyMopp在评论中发布的链接。



要查看特定的编译器认为1.18 * 100,您可以在双击)。

printf("%.16f * 100 = %.16f\n", 1.18, 1.18 * 100);

这篇关于问题与浮点重新presentation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆