我想将除以零的结果定义为double INF。
关于C / C ++中的默认行为(除以零)有一些讨论。(我读过)没有任何问题明确询问如何定义零除以在C中变为无穷大。这是否有意义,我宁愿不讨论。我只想用一个包含多个C函数的文件来定义它,并且需要它的语法。
Kon*_*lph 13
If you require this behaviour, use floating point numbers, which can represent infinity, and provide the desired behaviour. Note that technically this is undefined behaviour but in practice most compilers (all mainstream compilers for standard architectures) implement IEEE 754 semantics, e.g. GCC.
int main() {
float f = 42;
float g = f / 0.0f;
printf("%f\n", g);
}
Run Code Online (Sandbox Code Playgroud)
Output:
inf
Run Code Online (Sandbox Code Playgroud)
This is behaviour that can be relied on since it’s clearly documented by the compilers. However, when writing portable code make sure that you test these assumptions inside your code (e.g. by testing whether the preprocessor macro __STDC_IEC_559__, as well as compiler-specific macros are defined).
如果出于某种原因,对于整数值需要此行为,则唯一的办法就是创建自己的类型。像这样:
typedef struct {
int value;
bool is_inf;
bool is_nan;
} ext_int;
ext_int make_ext_int(int i) {
return (ext_int) {i, false, false};
}
ext_int make_nan() {
return (ext_int) {0, false, true};
}
ext_int make_inf(int sign) {
return (ext_int) {(sign > 0) - (sign < 0), true, false};
}
ext_int ext_div(ext_int a, ext_int b) {
if (a.is_nan || b.is_nan) {
return make_nan();
}
if (b.value == 0) {
return make_inf(a.value);
}
// TODO: insert other cases.
return (ext_int) {a.value / b.value, false, false};
}
Run Code Online (Sandbox Code Playgroud)
…在一个实际的实现中,您将打包不同的标志,而不是bool为每个标志单独包装。
C标准未定义浮点除以零。
(IEEE754-常见但绝非普遍存在-定义a / 0.0为+INFif a为正,-INFif a为负,NaNif a也为零)。
最好的选择是定义一个对除法运算符建模的函数,并在那里实现您的行为。