c - Inaccuracy when using pow() function -


i made program splits number numbers that, when added, give first number. example, 1234 should split 1000, 200, 30, , 4.

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>  int main () { int i, num1, num2; char tmp[6];  // number stored here string int num3 = 12345;  //the number   sprintf(tmp, "%d", num3); //convert string for(i = 0; < strlen(tmp); i++)  //check every digit {     num1 = pow(10, strlen(tmp) - 1 - i);  //every number multiplied 10                            //to power of number of digits - 1 - counter     num2 = tmp[i] - '0';   //convert character int     printf("%d\n", num1*num2); //print number }   return 0; } 

this output:

9999 2000 297 40 5 

as can see not correct, why?

the problem floating point calculations may have small errors. results of pow function may larger or smaller expected. when convert int, result truncated. example, if pow(10,4) returns 9999.999999, converting int yields 9999, not expected. on other hand, if pow(10,3) returns 1000.000001 converting int give expected result.

here's code should demonstrate problem (on computers results of pow function not exact):

int main( void ) {     ( int = 0; < 5; i++ )     {         double num1 = pow(10,i);         int num2 = num1;         printf( "%12f --> %5d\n", num1, num2 );     } } 

to avoid problem, either need round results of pow, or avoid floating point math altogether. here's code shows how solve problem using integer math.

int main( void ) {     char temp[] = "12345";     int length = strlen( temp );      int multiplier = 1;     ( int = 1; < length; i++ )         multiplier *= 10;      ( int = 0; < length; i++ ) {         printf( "%d\n", (temp[i] - '0') * multiplier );         multiplier /= 10;     } } 

Comments