Strange behaviour of the pow function

后端 未结 5 708
借酒劲吻你
借酒劲吻你 2020-11-22 12:23

While running the following lines of code:

int i,a;    

for(i=0;i<=4;i++)  
{    
    a=pow(10,i);    
    printf(\"%d\\t\",a);    
}   
5条回答
  •  日久生厌
    2020-11-22 13:11

    No one spelt out how to actually do it correctly - instead of pow function, just have a variable that tracks the current power:

    int i, a, power;    
    
    for (i = 0, a = 1; i <= 4; i++, a *= 10) {    
        printf("%d\t",a);    
    }
    

    This continuing multiplication by ten is guaranteed to give you the correct answer, and quite OK (and much better than pow, even if it were giving the correct results) for tasks like converting decimal strings into integers.

提交回复
热议问题