C# Logical Operator help

Associate
Joined
7 Nov 2008
Posts
1,410
Location
Edinburgh, Scotland
Hey,

I'm trying to do some coursework, but I cant seem to understand why this code isn't working. I get errors associated with the <= and the 10)

Code:
if (totalA + totalB >= 9 && <= 10)
{
txtResult.Text = ("i. Excellent if the overall score is 9-10");
}

As the code reads, i want the statement txtResult.... to occur if the total of totalA + totalB is greater than or equal to 9 and less than or equal to 10.

I've tried the OR operator too, ||, but still doesn't work.

Can anyone shine some light on this please?

Thanks in advance!

Em
 
You need to do
Code:
if (totalA + totalB >= 9 && totalA + totalB <= 10)
{
txtResult.Text = ("i. Excellent if the overall score is 9-10");
}

The two parts before and after the && are entirely separate and just because you're using totalA + totalB in the first bit the compiler has no idea that you want it in the second bit, you could be intending to compare something else entirely for all it knows.

Given this, it's probably a good idea to get the result of the sum as a separate variable and then use this in your if statement, like follows.

Code:
var total = totalA + totalB;
if (total >= 9 && total <= 10)
{
txtResult.Text = ("i. Excellent if the overall score is 9-10");
}
 
Ahh wicked,

I got around it just now by trial and error and came out with this:

Code:
if ((totalA + totalB >= 9) && (totalA + totalB <= 10))
{
txtResult.Text = ("i. Excellent if the overall score is 9-10");
}


But looking the code you suggested I can see that it would be the better choice.

Thanks very much for helping :)

Em
 
perhaps it's easier to read like so:

Code:
if (total == 9 || total == 10)

but I'm guessing this is the result of a quiz, so you probably want:

Code:
switch (total)
{
    case 10:
    case 9:
    {
        // msg
    }
    //etc
}
 
Back
Top Bottom