比较从字符串转换为文字的浮点值 [英] Comparing floating point values converted from strings with literals

查看:88
本文介绍了比较从字符串转换为文字的浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是著名的 浮点数学运算已被破坏的副本 ,即使乍一看也是如此.

我正在使用fscanf(file, "%lf", &value);从文本文件中读取double,并将其与==运算符与双精度字面值进行比较.如果字符串与文字相同,在所有情况下使用==进行的比较是否为true?

I'm reading a double from a text file using fscanf(file, "%lf", &value); and comparing it with the == operator against a double literal. If the string is the same as the literal, will the comparision using == be true in all cases?

示例

文本文件内容:

7.7

代码段:

double value;
fscanf(file, "%lf", &value);     // reading "7.7" from file into value

if (value == 7.7)
   printf("strictly equal\n");

预期和实际输出为

strictly equal

但是,这假定编译器将双精度文字7.7转换为double,与fscanf函数完全相同,但是编译器可能会或可能不会使用相同的库将字符串转换为double.

But this supposes that the compiler converts the double literal 7.7 into a double exactly the same way as does the fscanf function, but the compiler may or may not use the same library for converting strings to double.

否则,是否被问到:从字符串到double的转换会导致唯一的二进制表示形式,还是可能存在与实现相关的细微差别?

Or asked otherwise: does the conversion from string to double result in a unique binary representation or may there be slight implementation dependent differences?

现场演示

Live demonstration

推荐答案

关于C ++,来自cppreference可以读取:

[lex.fcon] (第6.4.4.2节)

[lex.fcon] (§6.4.4.2)

对浮点常量求值的结果是以实现定义的方式选择的最接近的可表示值或紧邻最接近的可表示值的较大或较小的可表示值(换句话说,转换期间的默认舍入方向为实现) -定义).

The result of evaluating a floating constant is either the nearest representable value or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner (in other words, default rounding direction during translation is implementation-defined).

由于未指定浮动文字的表示形式,因此我想您无法得出将其与scanf结果进行比较的结论.

Since the representation of a floating literal is unspecified, I guess you cannot conclude about its comparison with a scanf result.

关于C11(标准ISO/IEC 9899:2011):

About C11 (standard ISO/IEC 9899:2011):

[lex.fcon] (第6.4.4.2节)

[lex.fcon] (§6.4.4.2)

推荐做法

7浮动常量的转换时转换应与库函数(例如strtod)的字符串的执行时转换相匹配,并给出适合于两种转换的匹配输入,相同的结果格式和默认执行时间 四舍五入.

7 The translation-time conversion of floating constants should match the execution-time conversion of character strings by library functions, such as strtod, given matching inputs suitable for both conversions, the same result format, and default execution-time rounding.

很明显,对于C11,不能保证匹配.

So clearly for C11, this is not guaranteed to match.

这篇关于比较从字符串转换为文字的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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