Home > Back-end >  Is float always rounding?
Is float always rounding?

Time:10-02

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]);
}

CodePudding user response:

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 .

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related