A1RStack A1RStack - 2 months ago 6
C# Question

Comparing x,y to z to see which one is closer

I'm new to C# and making a small exercise where a user enters a value between 1 and 100 (x). The computer then proceeds to generate a random number to use for the game (y) and generates another random number for itself (z).

The program compares the value of x and z to y to see which value is closer to y.
I'm having some trouble doing the comparing stuff. It's more of a logical difficulty than it is coding wise. I'm relatively new so i pretty much suck at naming conventions.

class Roll
{
public int randomNumber { get; set; } //Random number for game
public int randomPc { get; set; } //Random number for pc

private void RandomGenerator() //Generates a number for int randomNumber and randomPc
{
Random rnd = new Random();
randomNumber = rnd.Next(1, 100);
randomPc = rnd.Next(1, 100);
}

public Roll(int user) //Is where the comparison takes place
{
RandomGenerator();
int compareUser;
int comparePc;

compareUser = user - randomNumber;
comparePc = randomPc - randomNumber;


if (compareUser < comparePc)
Console.WriteLine("\nPC won!\n{0} is closer to {1} than {2} is!", randomPc, randomNumber, user);



if (comparePc < compareUser)
Console.WriteLine("\nUser has won!\n{2} is closer to {1} than {0} is!", randomPc, randomNumber, user);


}

}


Thank you for your time.

Answer

You never thought of the case where the compareUser result is negative. Therefore, you are going to need to compute the difference between the two numbers, like a distance, and not just the math value user - randomNumber. We do that using Math.Abs() function.

Also your logic is missing the case were compareUser is = comparePc

This is how your logic should be:

public Roll(int user) //Is where the comparison takes place
{
    RandomGenerator();
    int compareUser;
    int comparePc;

    compareUser = Math.Abs(user - randomNumber); 
    comparePc = Math.Abs(randomPc - randomNumber);


    if (compareUser < comparePc)
        Console.WriteLine("\nPC won!\n{0} is closer to {1} than {2} is!", randomPc, randomNumber, user);

    else if (comparePc < compareUser)
        Console.WriteLine("\nUser has won!\n{2} is closer to {1} than {0} is!", randomPc, randomNumber, user);
    else
    {
       // compareUser == comparePc - do something
    }

}
Comments