无法从 MSVCRT strtod/sscanf/atof 函数获取 NaN
Can't get a NaN from the MSVCRT strtod/sscanf/atof functions
是否有办法从Windows CRT string
到float
函数获得NaN
s?
为什么:我正在用C编写IEEE float
到string
转换器,没有信息丢失(strtod
, sscanf
或atof
返回原始float
),前提是舍入模式不改变。
我在MinGW或Visual c++下,所以这些调用去msvc++运行时。问题是我无法让它解析任何特殊值(如"Inf"
或"NaN"
)。Inf
是OK的(在解析了不适合float
的值后返回,例如"1e999"
)。
/* Return the shortest string representation of a float with a successful scanf round-trip.
* Guaranteed to fit in 13 chars (including the final ' ').
*/
char* ftoa(char* res, float f) {
float r = 0;
int i, j, len, e = floor(log10(f)) + 1;
char fmt[8];
union { float f; int32_t i; } u = { f } ;
if (f > FLT_MAX) { sprintf(res, "1e999"); return res; }
if (f < -FLT_MAX) { sprintf(res, "-1e999"); return res; }
if ((u.i & 0x7F800000) == 0x7F800000) { // NaN
sprintf(res, u.i == 0x7FC00000 ? "%sNaN" : "%sNaN%d", u.i<0 ? "-" : "", u.i & 0x7FFFFF);
return res;
}
// compute the shortest string without exponent ("123000", "0.15")
if (!f || e>-4 && e<10) {
for (i=0; i<=10; i++) {
sprintf(fmt, "%%.%df", i);
sprintf(res, fmt, f);
sscanf(res, "%f", &r); if (r==f) break;
}
}
if (r==f) len = strlen(res);
else len = 1e9;
if (!f) return res; // handle 0 and -0
// compute the shortest string with exponent ("123e3", "15e-2")
for (i=0; i<9; i++) {
sprintf(res, "%.0fe%d", f * pow(10,-e), e); sscanf(res, "%f", &r); if (r==f) break;
j = strlen(res); if (j >= lenF) break;
while (res[j] != 'e') j--;
res[j-1]--; sscanf(res, "%f", &r); if (r==f) break; // try +-1
res[j-1]+=2; sscanf(res, "%f", &r); if (r==f) break;
e--;
}
if (len <= strlen(res)) sprintf(res, fmt, f);
return res;
}
No。如果发生溢出,则返回HUGE_VAL;如果输入无法解析或发生下溢,则返回0。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- atof 函数在程序中不起作用
- 如何在不使用 atof 函数的情况下将命令行添加为数字数据
- 无法从 MSVCRT strtod/sscanf/atof 函数获取 NaN