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

后端 未结 7 1142
面向向阳花
面向向阳花 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:30

    All operations are done on objects of the same type (assuming normal arithmetic operations).

    If you write a program that uses different types then the compiler will auto upgrade ONE parameter so that they are both the same.

    In this situations floats will be upgraded to doubles:

    result      = a * (b + c) * d
    
    float  tmp1 = b + c;            // Plus operation done on floats.
                                    // So the result is a float
    
    double tmp2 = a * (double)tmp1; // Multiplication done on double (as `a` is double)
                                    // so tmp1 will be up converted to a double.
    
    double tmp3 = tmp2 * d;         // Multiplication done on doubles.
                                    // So result is a double
    
    result      = tmp3;             // No conversion as tmp3 is same type as result.
    
    0 讨论(0)
提交回复
热议问题