Home > Enterprise >  Range of Integers
Range of Integers

Time:10-17

C#. I would like to compare a random number to a guess. If the guess is 3 more or 3 less than the random number , the program should show the statement Console.WriteLine("Almost right"); Can I write like this?

If (randomnumber < guess 3 | randomnumber> guess-3);
Console.Writeln ("Almost right")

I am not using array.

Is there a more efficient way to write the code?

CodePudding user response:

You are on the right track.

When you write code here, you can and should write it as code, read the markdown spec or get accustomed to the editor here at stackoverflow. code looks like:

If (randomnumber < guess 3 | randomnumber> guess-3); Console.Writeln ("Almost right")

You should then write real code because your code is more c# like pseudo code. Correctly you must write:

if (randomnumber < guess 3 || randomnumber> guess-3) {
     Console.Writeln ("Almost right");
}

Check the logical operators in C#, its || not |

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators

Performance wise this is fine you could write a specific method like

bool IsRoughly (x, y) {
   return x < y   3 || y < x   3;
}

This puts the esence of your logic more into light. Finally you have to think about the corner cases: Is 1 really almost the maximum value of an int? Probably not.

CodePudding user response:

With C# 9 you can do in easy readable way. These are just alternative ways do to the the same thing in bit different way

if (randomnumber is < (guess 3) or randomnumber is > (guess-3))
{
    Console.WriteLine("Almost right");
}

Another alternative way is to use

if(Enumerable.Range(guess - 2, guess   2).Contains(randomnumber))
  • Related