[英]std::cout does not print float as excepted
Why does std::cout << 1.00000001;
为什么
std::cout << 1.00000001;
print 1
to the console?打印
1
到控制台? It Works fine with 1.0001
, Its only after it exceeds a certain precision when it stops printing it properly.它适用于
1.0001
,只有在超过一定精度后才能正确停止打印。
These numbers are hard coded, so this question is not a duplicate.这些数字是硬编码的,所以这个问题不是重复的。 In that question, an irrational number was produced because two floating point numbers were added, which means the numbers could not be stored properly, but in my case the numbers are hard coded, so what is the reason for not being able to print (or store maybe) a float explicitly initialised as
1.00000001
?.在那个问题中,由于添加了两个浮点数,所以产生了一个无理数,这意味着这些数字无法正确存储,但在我的情况下,这些数字是硬编码的,所以无法打印的原因是什么(或存储可能)一个浮点数显式初始化为
1.00000001
? Is it just cout
failing to print the value or is it really an int
?只是
cout
无法打印值还是真的是int
?
Consider the following program考虑以下程序
int main()
{
float num = 1.0000001f;
float num2 = num * 2;
std::cout << num;
std::cout << num2;
}
num2
prints 2
but the complier does not give a warning about conversion from float
to int
in line 2
, so I think that num
must be a float
. num2
打印2
但编译器在line 2
没有给出关于从float
转换为int
的警告,所以我认为num
必须是float
。 Does that mean it's just a problem with cout
?这是否意味着这只是
cout
的问题? Am I safe to assume that internally num
is actually 1.0000001f
even though it prints 1
to the console?我可以安全地假设内部
num
实际上是1.0000001f
即使它在控制台上打印1
?
My complier is visual studio 2019's inbuilt one.我的编译器是 Visual Studio 2019 的内置编译器。
Summarizing my comments:总结我的评论:
So if you play a bit with this converter , you can see that after 1, the next float values are:所以如果你玩一下这个转换器,你可以看到在 1 之后,下一个浮点值是:
1.0000001 falls in between the first two, so your compiler can choose either. 1.0000001 介于前两者之间,因此您的编译器可以选择其中任何一个。 In your case it seems your compiler picked 1.
在您的情况下,您的编译器似乎选择了 1。
(also for printing operations, cout operations will truncate digits after a defined precision, so it does not show the full numbers I put above - that precision defaults to 6 digits). (同样对于打印操作, cout 操作将在定义的精度后截断数字,因此它不会显示我在上面输入的完整数字 - 该精度默认为 6 位)。
The default precision I believe is 6 digits for you, but they are all zeroes.我相信你的默认精度是 6 位,但它们都是零。 So they don't print.
所以他们不打印。
#include <iostream>
#include <iomanip>
int main()
{
std::cout << std::setprecision(10);
// this is what you had
float f1 = 1.0000001f;
float f2 = f1 * 2;
std::cout << f1 << std::endl;
std::cout << f2 << std::endl;
// any more zeroes and it would have been idistinguishable from 1.0
f1 = 1.00000001f;
f2 = f1 * 2;
std::cout << f1 << std::endl;
std::cout << f2 << std::endl;
}
1.000000119
1.000000119
2.0000002382.000000238
11
22
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.