L
L
LebedevStr2019-03-29 19:11:25
C++ / C#
LebedevStr, 2019-03-29 19:11:25

How to stop IF slippage in C#?

There is such a code

if (value > 0.5 && value < 0.75);
                                        value = value + onePercent * 150;
                                        
                                    if (value > 0.75 && value < 1);
                                    value = value + onePercent * 125;
                                    
                                    if (value > 1 && value < 2);
                                    value = value + onePercent * 100;

The bottom line is, value (number) slips through all IFs, and is multiplied on each operation.
That is, the number 3.05 turns into 25.19.
How to "stop" the multiplication after the first function?
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dasha Tsiklauri, 2019-03-29
@LebedevStr

instead of the second and third if use else if

if () {
} else if () {
}

V
Vladimir T, 2019-03-29
@32bit_me

No, no, no, not like this:

if (value > 0.75 && value < 1);
                                    value = value + onePercent * 125;

But like this:
if (value > 0.75 && value <= 1) {
                                    value = value + onePercent * 125;
}

or, at worst, like this:
if (value > 0.75 && value <= 1) 
                                    value = value + onePercent * 125;

Look, you have a semicolon after the condition, which means that the conditional statement is over here, and the next line will always be executed.
And write the conditions so that they cover the entire range, i.e. if you have a condition x < 1.0 in one if, then the next should have x >= 1.0 or vice versa, or better use if... else...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question