gpt4 book ai didi

floating-point - 58.85显示为58.84999999999

转载 作者:行者123 更新时间:2023-12-04 18:11:45 26 4
gpt4 key购买 nike

我正在使用BSP构建计算器。
当我用各种数字测试它时,我遇到了一个问题,即十进制数字无法正确显示。

例如。
58.85-> 58.849999。但是58.84或58.86可以正常工作。
58.8471-> 54.84710000000001。最后输入的数字将被无处保存。

我的代码如下。

method GENERATE_NUM.

DATA: lv_digi type I. * number of digits after the decimal point


call METHOD me->get_decimal
RECEIVING
getdigits = lv_digi.

*if it is a natural number
IF lv_digi = 0.
IF thisnum < 0.
result = thisnum * 10 - newdigit.
ELSE.
result = thisnum * 10 + newdigit.
ENDIF.

*if it is a float number
Else.
IF thisnum < 0.
result = thisnum - ( newdigit / 10 ** lv_digi ).
ELSE.
result = thisnum + ( newdigit / 10 ** lv_digi ).
ENDIF.

*increase the number of decimal point by 1
call method me->set_decimal.
ENDif.

endmethod.

我基本上要做的是每次单击数字时,它就会调用“generate_num”方法。
它以THISNUM,NEWDIGIT,RESULT作为参数。
thisnum =当前数字(例如:58.8)
newdigit =点击的数字(例如:5)
结果=生成的数字(预期值:58.85,但返回58.849999)。

最佳答案

如果要使用固定精度的十进制数字,则应使用类型P(带包装的数字)而不是浮点数。

例子:

DATA lv_fixed_point TYPE p LENGTH 16 DECIMALS 2.

这将创建一个定点变量,该点后面有两位数字。 “length”参数的确切含义不是那么简单。从 documentation:

Packed numbers - type P

Type P data allows digits after the decimal point. The number of decimal places is generic, and is determined in the program. The value range of type P data depends on its size and the number of digits after the decimal point. The valid size can be any value from 1 to 16 bytes. Two decimal digits are packed into one byte, while the last byte contains one digit and the sign. Up to 14 digits are allowed after the decimal point. The initial value is zero. When working with type P data, it is a good idea to set the program attribute Fixed point arithmetic.Otherwise, type P numbers are treated as integers.

You can use type P data for such values as distances, weights, amounts of money, and so on.

关于floating-point - 58.85显示为58.84999999999,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12402029/

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