所以我得到了这个任务,我应该写一个c#程序,让用户输入两个数字。如果其中一个输入为正,另一个输入为负,程序应该返回true。我试过以下方法,但我没有得到它的工作。什么好主意吗?
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.");
}
}
你离解决问题很近了。如果您更改:
if (num1 > 0; num2 < 0)
这:
if (num1 > 0 && num2 < 0)
并去掉"()"在else语句之后,您将获得所需的结果。分号假定它是序列的结尾。我建议您查看布尔运算符以了解更多信息:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators
在这两个条件之间需要一个逻辑和运算符(即&&
)。此外,在else
:
()
)。if (num1 > 0 && num2 < 0) // Note the usage of &&
{
Console.WriteLine("Correct input.");
}
else // () removed here
{
Console.WriteLine("Wrong input.");
}
c#中的AND操作符是'&&',所以在代码行中你应该用'&&':
if (num1 > 0 && num2 < 0)
{
Console.WriteLine("Correct input.");
}
你还需要去掉else后面的圆括号,因为它不表示任何参数
if (*condition*)
{
}
else
{
}
注意:如果使用OR比较器,则使用||