否则块不工作

本文关键字:工作 | 更新日期: 2023-09-27 18:14:42

每当我输入一个无效的数字(例如数字太长,或字母)作为分母时,我总是得到"NOtZero"。我的If/Else语句逻辑错误。出了什么问题,我该如何解决这个问题?

static void Main(string[] args)
{
   Console.WriteLine("Enter Numerator");
   int numerator;
   bool IsNumeratorConverstionSucess=Int32.TryParse(Console.ReadLine(), out numerator);
    if (IsNumeratorConverstionSucess)
    {
        Console.WriteLine("Enter Denominator");
        int denominator;
        bool IsdenominatorConverstionSucess = Int32.TryParse(Console.ReadLine(), out denominator);
        if (IsdenominatorConverstionSucess && denominator != 0)
        {
            int result = numerator / denominator;
            Console.WriteLine("Result is = {0}", result);
        }
        else
        {
            if(denominator==0)
            {
                Console.WriteLine("NOtZero");
            }
            else
            {
            Console.WriteLine("Deominator Should Be A Valid Number Between {0} To {1} Range", Int32.MinValue, Int32.MaxValue);
            }
        }
    }
    else
    {
        Console.WriteLine("Numerator Should Be A Valid Number Between {0} To {1} Range",Int32.MinValue,Int32.MaxValue);
    }
}

否则块不工作

当您输入无效的分母时,您获得"NOtZero"的原因是因为int.tryparse在失败时将其out参数设置为0。因此,当您为分母值输入a时,您的代码将使用以下工作流:

  1. 实例化变量denominator
  2. 尝试将用户输入转换为整数,并返回给denominator
  3. 转换失败,返回false,将denominator设为0

Johnie Karr是对的,你的逻辑失败了,因为如果解析失败,分母将始终为0。

另一种方法是将零检查逻辑移到成功分支中。

if (IsdenominatorConverstionSucess)
{
    if(denominator==0)
    {
        Console.WriteLine("NOtZero");
    }
    else
    {
        int result = numerator / denominator;
        Console.WriteLine("Result is = {0}", result);
    }
}
else
{
    Console.WriteLine("Denominator Should Be A Valid Number Between {0} To {1} Range", Int32.MinValue, Int32.MaxValue);
}