0

I made a program that splits a number into numbers that, when added, give the first number. For example, 1234 should be split into 1000, 200, 30, and 4.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main ()
{
int i, num1, num2;
char tmp[6];  // the number will be stored here as string
int num3 = 12345;  //the number 

sprintf(tmp, "%d", num3); //convert to string
for(i = 0; i < strlen(tmp); i++)  //check every digit
{
    num1 = pow(10, strlen(tmp) - 1 - i);  //every number will be multiplied by 10
                           //to the power of number of digits - 1 - counter
    num2 = tmp[i] - '0';   //convert character to int
    printf("%d\n", num1*num2); //print the number
}

 return 0;
}

This is the output:

9999
2000
297
40
5

As you can see this is not correct, why?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
user3711671
  • 823
  • 1
  • 6
  • 13

1 Answers1

-1

The problem is that floating point calculations may have small errors. Which is to say that the results of the pow function may be slightly larger or slightly smaller than expected. When you convert to an int, the result is truncated. For example, if pow(10,4) returns 9999.999999, then converting to an int yields 9999, which is not what you expected. On the other hand, if pow(10,3) returns 1000.000001 then converting to an int will give the expected result.

Here's some code that should demonstrate the problem (on computers where the results of the pow function are not exact):

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

To avoid the problem, you either need to round the results of pow, or avoid floating point math altogether. Here's some code that shows how to solve the problem using only integer math.

int main( void )
{
    char temp[] = "12345";
    int length = strlen( temp );

    int multiplier = 1;
    for ( int i = 1; i < length; i++ )
        multiplier *= 10;

    for ( int i = 0; i < length; i++ ) {
        printf( "%d\n", (temp[i] - '0') * multiplier );
        multiplier /= 10;
    }
}
user3386109
  • 34,287
  • 7
  • 49
  • 68