Home > Back-end >  How to return true if one number(asked by program) is positive and the other one(also asked by progr
How to return true if one number(asked by program) is positive and the other one(also asked by progr

Time:09-29

So i got this assignment that I should write a c# program that lets the user type in two numbers. The program should then return true if one of the inputs is positive and the other one negative. I've tried the following but I don't get it to work. Any ideas?

static void check()
    {
        Console.WriteLine("Type in a positive number:");
        int num1 = int.Parse(Console.ReadLine());
        Console.WriteLine("Type in a negative number:");
        int num2 = int.Parse(Console.ReadLine());


        if (num1 > 0; num2 < 0)
        {
            Console.WriteLine("Correct input.");
        }       
        else()
        {
         Console.WriteLine("Wrong input.");
        }
    }

CodePudding user response:

You are very close to a solution. If you change:

if (num1 > 0; num2 < 0)

into this:

if (num1 > 0 && num2 < 0)

And remove the "()" after your else statement you will get your desired result. The semicolon assumed that it is the end of a sequence. I would recommend you to look at boolean operators to find out more:

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

CodePudding user response:

You need a logical and operator (i.e., &&) between the two conditions. Additionally, there should be no parentheses (()) after the else:

if (num1 > 0 && num2 < 0) // Note the usage of &&
{
    Console.WriteLine("Correct input.");
}       
else // () removed here
{
    Console.WriteLine("Wrong input.");
}

CodePudding user response:

The AND operator sytnax in C# is '&&' so in the line of code you should replace ';' with '&&':

 if (num1 > 0 && num2 < 0)
        {
            Console.WriteLine("Correct input.");
        }       

You also need to remove the parentheses after else since it does not denote any arguments

if (*condition*)
{
}
else
{
}

N.B. if you where using an OR comparator you would use ||

  • Related