C++中怎么避免被0除

C++中怎么避免被0除,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

Reason(原因)

The result is undefined and probably a crash.

结果无定义,很可能会导致程序崩溃。

Note(注意)

This also applies to %.

本规则也适用于取余运算。

Example, bad(反面示例)

double divide(int a, int b)
{
   // BAD, should be checked (e.g., in a precondition)
   return a / b;
}
Example, good(范例)
double divide(int a, int b)
{
   // good, address via precondition (and replace with contracts once C++ gets them)
   Expects(b != 0);
   return a / b;
}

double divide(int a, int b)
{
   // good, address via check
   return b ? a / b : quiet_NaN<double>();
}

Alternative: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.

可选项:对于能够承受一定代价的要求严格的应用,可以考虑使用带有范围检查的整数或者浮点数。

Enforcement(实施建议)

  • Flag division by an integral value that could be zero

  • 标记可能为零的整数除数。


关于C++中怎么避免被0除问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。