Home > Back-end >  Why is my code not reversing a two digit number?
Why is my code not reversing a two digit number?

Time:07-20

I am trying to reverse a two digit number, and I understand there may be better ways of doing this, but I am curious now why the way I chose does not work.

If I input 48, it produces 84 (a successful reversal).

If I input 84, it produces 38. If I input 47, it produces 64. These are just some examples of unsuccessful reversals.

    int digit_one, digit_two, input;
    float a, b;

    printf("Enter a two-digit number: ");
    scanf("%d", &input);

    a = input * 0.1; // turns the two digit input figure into a float with a digit after the decimal point
    digit_one = a; // turns the float into an integer, eliminating the digit after the decimal point

    b = a - digit_one; // produces a float that has a 0 before the decimal point, and a digit after the decimal point
    digit_two = b * 10; // moves the digit that was after the decimal point, to before the decimal point

    printf("The reversal is: %d%d\n", digit_two, digit_one);

Thank you!

CodePudding user response:

a - digit_one is a fractional number. If it's slightly less than the exact result (because for example 0.7 cannot be represented exactly as a float), then (a - digit_one) * 10 will be slightly less than the desired integer, and so digit_two will be one less than you expect.

You can avoid floating point, and write int digit_one, digit_two = input / 10, input % 10;

CodePudding user response:

Working with floats is not the best approach here. With the input "84", b * 10 = 3.999996 which is 3 when you convert it to an integer.

This is a classic computer science problem with floats. Here are some links where this has been explained very well:

Is floating point math broken?

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Your problem can be solved differently:

int digit_one, digit_two, input, a, b;

printf("Enter a two-digit number: ");
scanf("%d", &input);

digit_one = input % 10;
digit_two = (input / 10) % 10;

printf("The reversal is: %d%d\n", digit_one, digit_two);
  •  Tags:  
  • c
  • Related