Home > Software engineering >  My code for changing the value of a float variable doesnt work
My code for changing the value of a float variable doesnt work

Time:07-11

Please explain why this doesnt work, I'm new to this.

float x = 1;
float y = 4.5578;
while (x >= 1)
{
    x = y - 1.0;
}
printf("%f", x);

I know you can fix the code like this

float y = 4.5578;
float x = 0;
while (x >= 0)
{
    x--;
}
printf("%f", x);

but i want to know why the previous doesnt work

CodePudding user response:

In your first snippet, there is no change in the loop - as in, you are changing x to be y - 1 each time and y does not change - goes into infinite loop!

In the second version, x does actually change and stop the loop

CodePudding user response:

float x = 1;
float y = 4.5578;
while (x >= 1)
{
    x = y - 1.0;
}
printf("%f", x);

This code has a value below when it started.

x = 1
y = 4.5578

and, the while will end when the x value is lower than 1.

At the first loop, x will be changed.

x = 3.5578
y = 4.5578

So, x was changed, but y wasn't changed. next loop, also x will be '4.5578 - 1.0' and its value is '3.5578'.

That's the problem. This loop will be ended when the x value will be decreased under 1.0. But, this loop doesn't change the y value, so the x value also didn't change whatever your loop.

The loop will be endless, and this is the error.

if you want to do this code, you have to do it like this.

float x = 1;
float y = 4.5578;

float times = 1.0;
while (x >= 1)
{
    x = y - times;
    times  = 1.0;
}
printf("%f", x);

This will be increased 'times' when the loop is finished, so seconded loop, the value of the x and y will be changed like below.

first loop

x = 3.5578
y = 4.5578
times = 1.0 (when loop ends, times will be increased to 2.0. this value is only when you calculate x and y.)

second loop

x = 2.5578
y = 4.5578
times = 2.0

third loop

x = 1.5578
y = 4.5578
times = 3.0

forth loop

x = 0.5578
y = 4.5578
times = 4.0

Then, boom! The x's value will be decreased under 1.0, so while loop will be ended. and

printf("%f", x);

will be showing 0.5578 when loop will be end.

The times' value will be '5.0' when this code ended, but that's not an error or something. This code will be increased 'times' when x = y - times calculate will end, so it gets increased that doesn't care about while loop will end.

If you want to end with a 'times' value is '4.0', you have to write code like the below.

float x = 1;
float y = 4.5578;

float times = 0.0;
while (x >= 1)
{
    times  = 1.0;
    x = y - times;

}
printf("%f", x);
  • Related