0

Here is my program, it turn decimal to base-"n", you can put number in "n" base what you want to turn to, it run successful but I have a question, I don't get it why the if ((float)input / (float)n <= 0) can pass in the fifth time. I'm debugging with vscode and watch the value every breakpoints and steps, here are the result

(run this line if ((float)input / (float)n <= 0))

input=20, n=2

First time : 20/2=10 (pass)

Second time : 10/2=5 (pass)

Third time : 5/2=2.5 (pass)

Forth time : 2.5/2=1 (pass) I don't understand why it is "1" not "1.25" (I think this is my main problem, is float always rouding ?)

Fifth time : 1/2=0.5 (pass)

Sixth time : 0.5/2=0 (fail and break)

Hope somebody can explain that I'll very appreciate, English not my mother tongue so forgive me.

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

void rev(int num[]);

int cnt = 0;

int main()
{

int input = 20, num[10], i, n = 2;

// Decimal turn to base-n

printf("Decimal \"%d\" to base-%d = ", input, n);

for (i = 0; i < 10;)
{
    if ((float)input / (float)n <= 0)
        break;
    else
    {
        num[i] = input % n;
        input /= n;
        i++;
        cnt++;
    }
}
rev(num);

printf("\n");

system("pause");
return 0;
}

void rev(int num[])
{
int i;

i = cnt - 1;

for (i; i >= 0; i--)
    printf("%d", num[i]);
}
jsn
  • 35
  • 5
  • 4
    Note that `(float)input / (float)n` uses floating-point division (e.g. `5.0 / 2.0 == 2.5`), but `input /= n` uses integer division (e.g. `5 / 2 == 2`). – 0x5453 Oct 01 '21 at 15:23
  • 2
    _Is `float` always rounding?_ Yes, a `float` is 4 bytes, a finite amount of storage, so you can only represent a finite amount of data. This is true no matter how large your data field is. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – yano Oct 01 '21 at 15:24
  • @0x5453 I understand what you say, integer division won't save the float. Thank you so much I think my problem solved. – jsn Oct 01 '21 at 15:28

2 Answers2

0

absolutely will be fail because . when you type casting float to int like int a = 3.14 ; just the decimal part will be stored exp int a = 0.5; means a equal to 0 .

fares
  • 97
  • 1
  • 5
0

When you divide input by n, you're doing integer division:

input /= n;

Integer division has an integer result. And either way, you're storing the result back to an integer, so any fractional portion is discarded.

So the values stored in input each time through the loop will be 20, 10, 5, 2 (not 2.5), 1, and 0.

John Bode
  • 119,563
  • 19
  • 122
  • 198