unusual output from pow

前端 未结 3 1301
面向向阳花
面向向阳花 2020-12-11 20:38

The following C code

int main(){
    int n=10;    
    int t1=pow(10,2);
    int t2=pow(n,2);
    int t3=2*pow(n,2);
    printf(\"%d\\n\",t1);
    printf(\"%         


        
3条回答
  •  离开以前
    2020-12-11 20:53

    Store the result computations as doubles. Print as double, using %f instead of %d. You will see that the 99 is really more like 99.999997, and this should make more sense.

    In general, when working with any floating point math, you should assume results will be approximate; that is, a little off in either direction. So when you want exact results - like you did here - you're going to have trouble.

    You should always understand the return type of functions before you use them. See, e.g. cplusplus.com:

    double pow (double base, double exponent); /* C90 */
    

    From other answers I understand there are situations when you can expect pow or other floating-point math to be precise. Once you understand the necessary imprecision that plagues floating point math, please consult these.

提交回复
热议问题