if (x <= 22.5f)
            {            

            }
            if (x >= 22.5f && x <= 67.5f)
            {

            }
            if (x >= 67.5f && x <= 112.5f)
            {

            }
            if (x >= 112.5f && x <= 157.5f)
            {

            }
            if (x >= 157.5f && x <= 180.0f)
            {

            }

My code seems too complex in its current form. I reckon there must be a more efficient way of doing the above. Can someone lend me their ideas?

Two things

if (x <= 22.5f)
{
}
if (x >= 22.5f && x <= 67.5f)
{
}

In statements like these, if the value is exactly 22.5f, then you're allowing control to enter each of these if statement. One way of stating intent is if one statement is <=, then the next one should simply be >. We could fix that up and call it a day. But we won't.

The second thing is that you are using seperate if statements for each check. Even if the value fits the first if statement, the way your program is constructed means that every following statement is still going to be evaluated. Rewrite the remaining statements as "else if". That way, when control finds a valid condition, none of the others are checked. Also, doing so means you can drop the first part of the conditional. if x <= 22.5f, you know control will enter the first block. So the second check does not need to worry about x being > 22.5, only if it is less than 67.5f.

if (x <= 22.5f)
{
}
else if (x <= 67.5f)
{
}
else if (x <= 112.5f)
{
}
else if (x <= 157.5f)
{
}
else if (x <= 180.0f)
{
}
commented: I gues my age must make me slower, I was on the point of posting exactly the same! +6

Thank you apegram.

Time for me to look at "else if" in detail!

Happy Easter. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.