What are the rules governing C++ single and double precision mixed calculations?

后端 未结 7 1168
面向向阳花
面向向阳花 2020-12-03 22:29

For example, these variables:

result (double)
a (double)
b (float)
c (float)
d (double)

A simple calculation:

result = a *          


        
7条回答
  •  温柔的废话
    2020-12-03 23:28

    You have to differentiate between type conversion and value conversion. The C++ standard (C as well) allows floating-point calculations to be done at extended precision.

    "The values of the floating operands and the results of floating expressions may be represented in greater precision and range than that required by the type; the types are not changed thereby."

    As types, b + c is an addition of two float(s). The result is a float. The result is then type promoted to a double and the two multiplications are done as doubles with a result of double.

    However, an implementation is allowed to do all the calculations, including b + c, using doubles (or higher precision). Indeed, I tried it out using Visual C++ and it did all the calculations using the 80-bit floating-point stack available on x86.

提交回复
热议问题