【发布时间】:2016-07-29 13:58:19
【问题描述】:
我在 mac 上尝试了以下代码,输出对我来说有点奇怪。
float a = 2.225;
float b = 123.235;
printf("round: %.2f %.2f \n", a, b);
printf("round: %.2f %.2f \n", 2.225, 123.235);
输出:
round: 2.22 123.24
round: 2.23 123.23
g++ --版本
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
印刷中的四舍五入规则是什么?在这两种情况下如何获得相同的打印结果? 非常感谢。
【问题讨论】:
-
我认为区别在于
floats 和doubles。 -
问题不在于打印——你得到不同的输出,因为你传递了不同的输入。在第一种情况下,当您将
double值分配给float变量时,您会失去精度。 -
这是出现“C/C++”标签问题的问题之一。代码中没有任何专门针对 C++ 的内容。这应该重新标记C吗? C 标签是否应该添加?在“C”标签下是否应该有另一个问题问同样的事情?我放弃了。