如果将类型留给编译器解析,为什么精度会丢失?

Why is precision lost if resolving of the type left to the compiler?

变量的小数类型留给编译器定义会导致精度丢失的原因是什么?这在任何地方都有记录吗?

DATA: gv_1 TYPE p LENGTH 15 DECIMALS 2 VALUE '56555.31'.
DATA: gv_2 TYPE p LENGTH 15 DECIMALS 2 VALUE '56555.31'.
DATA: gv_3 TYPE p LENGTH 15 DECIMALS 2 VALUE '56555.34'.

DATA(gv_sum) = gv_1 + gv_2 + gv_3. "data type left to be resolved by the compiler

WRITE / gv_sum.

DATA: gv_sum_exp TYPE p LENGTH 15 DECIMALS 2. "explicit type declaration
gv_sum_exp = gv_1 + gv_2 + gv_3.

WRITE / gv_sum_exp.

第一个和的结果是

169666

中的第二个

169665.96

众所周知,ABAP编译器将一个算术表达式的所有操作数带入所谓的calculation type。而我们也知道取值范围最大的数据类型决定了整个计算类型。
但是您可能不知道随着 ABAP 中内联声明的发布而引入到此过程中的一些更改。他们在这里:

If operands are specified as generically typed field symbols or formal parameters and an inline declaration DATA(var) is used as the target field of an assignment, the generic types contribute to the statically detectable calculation type (used to determine the data type of the declaration) as follows:
...
csequence, clike, c, n, and p like p. If no type with a higher priority is involved, the type p with length 8 (no decimal places) is used for the declaration.
...

这正是我们在执行您的代码期间在调试器中看到的: