我在 C++ 中遇到了一个奇怪的行为。
运行以下行会导致浮点异常:
long double res = 0 / 0 * 100;
Run Code Online (Sandbox Code Playgroud)
但是,运行以下几行会导致变量res打印为 -nan:
long double res = static_cast<long double>(0) / 0 * 100;
std::cout << res << std::endl;
Run Code Online (Sandbox Code Playgroud)
谁能澄清为什么会发生这种情况?在什么条件下,计算结果为“nan”,何时会引发除以 0 的异常作为“浮点异常”?
这是我当前的代码:
// Yes, the missing single quotation mark is intentional
static void replace_punctuation(char *s, size_t len)
{
static const unsigned char punctuation[] = ".,;:!?\"()[]{}-";
for (size_t i = 0; i < len; ++i) {
if (memchr(punctuation, s[i], sizeof punctuation - 1)) {
s[i] = ' ';
}
}
}
Run Code Online (Sandbox Code Playgroud)
对程序进行分析(cachegrind/Kcachegrind)(在启用优化的情况下编译,-O2)后,发现这是一个瓶颈。
s不是以 null 结尾的字符串,因此strpbrk()不能使用。
如何对其进行优化?