每当我为分母输入无效数字(例如数字太长或字母)时,我总是得到“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);
}
}
答案 0 :(得分:1)
当您输入无效分母时,您获得“NOtZero”的原因是因为int.tryparse
在失败时将其out参数设置为0。因此,当您为分母值输入a
时,您的代码正在使用以下工作流程:
denominator
denominator
false
,将denominator
设置为0 答案 1 :(得分: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);
}