使用&&和||取代&和|的原因

如果使用&或者|,则在if判断括号中的第一个条件为0的时候它依旧会继续去判断第二个条件,但是如果第二个条件中的除数为 0 的时候就会让程序出现错误,抛出run-time异常。

Console.Write("Enter a dividend: ");
var dividend = Convert.ToInt32(Console.ReadLine());

Console.Write("Enter a divisor: ");
var divisor = Convert.ToInt32(Console.ReadLine());

// If the divisor is 0, the second clause in the following condition
// causes a run-time error. The && operator short circuits when the
// first expression is false. That is, it does not evaluate the
// second expression. The & operator evaluates both, and causes
// a run-time error when divisor is 0.
if ((divisor != 0) && (dividend / divisor > 0))
{
    Console.WriteLine("Quotient: {0}", dividend / divisor);
}
else
{
    Console.WriteLine("Attempted division by 0 ends up here.");
}
posted @ 2020-08-10 10:39  艾孜尔江  阅读(152)  评论(0编辑  收藏  举报