除以零预防 [英] Divide by zero prevention

查看:170
本文介绍了除以零预防的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是 1.#INF 和为什么转换到 float double 防止除以0除以崩溃?

此外,任何伟大的想法如何防止除以0? (像任何宏或模板一样)?

What is 1.#INF and why does casting to a float or double prevent a division by 0 of crashing?
Also, any great ideas of how to prevent division by 0? (Like any macro or template)?

int nQuota = 0;

int nZero = 3 / nQuota; //crash
cout << nZero << endl;

float fZero = 2 / nQuota; //crash
cout << fZero << endl;

如果我改用:

int nZero = 3 / (float)nQuota;
cout << nZero << endl;
//Output = -2147483648

float fZero = 2 / (float)nQuota;
cout << fZero << endl;
//Output = 1.#INF


推荐答案

1.#INF 是正无穷大。当你将一个正浮点除以零(如果你将浮点零本身除以零,那么结果将是不是一个数字)。你会得到。

1.#INF is positive infinity. You will get it when you divide a positive float by zero (if you divide the float zero itself by zero, then the result will be "not a number").

原因 float fZero = 2 / nQuota;

The reason float fZero = 2 / nQuota; crashes is because both operands of the / operator are integers, so the division is performed on integers. It doesn't matter that you then store the result in a float; C++ has no notion of target typing.

为什么正无穷强制转换为整数是最小的整数,我不知道。

Why positive infinity cast to an integer is the smallest integer, I have no idea.

这篇关于除以零预防的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆