【问题标题】:How to return true if one number(asked by program) is positive and the other one(also asked by program) is negative如果一个数字(程序要求)为正而另一个(程序要求)为负,如何返回 true
【发布时间】:2021-09-28 17:56:36
【问题描述】:

所以我得到了这个任务,我应该编写一个 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.");
        }
    }

【问题讨论】:

  • 您想使用&amp; 运算符。 if (num1 &gt; 0 &amp; num2 &lt; 0)read more here
  • 除整数之外,还需要检查其他数字吗?

标签: c# console-application


【解决方案1】:

您非常接近解决方案。如果你改变:

if (num1 > 0; num2 < 0)

进入这个:

if (num1 > 0 && num2 < 0)

并删除 else 语句后的“()”,您将获得所需的结果。分号假定它是序列的结尾。我建议您查看布尔运算符以了解更多信息:

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

【讨论】:

  • 谢谢!现在效果很好。
【解决方案2】:

在这两个条件之间需要一个逻辑和运算符(即&amp;&amp;)。此外,else 后面不应有括号(()):

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

【讨论】:

    【解决方案3】:

    C# 中的 AND 运算符 sytnax 是 '&&' 所以在代码行中你应该替换 ';'带有'&&':

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

    你还需要删除 else 后面的括号,因为它不表示任何参数

    if (*condition*)
    {
    }
    else
    {
    }
    

    注意如果你使用 OR 比较器,你会使用 ||

    【讨论】:

      猜你喜欢
      • 2012-07-06
      • 1970-01-01
      • 2015-06-29
      • 2012-08-30
      • 1970-01-01
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多