只要使用浮点数,0.1就不能在内存中精确表示,所以我们知道这个值通常是0.10000000000000004。
但是当使用go时加0.1和0.2。 我得到0.3。
#include <iostream>
#include <array>
#include <algorithm>
using namespace std;
int main(){
char x;
std::array<string, 4> supplies{"apple", "banana" , "egg", "love"};
std::array<string, 4> shopping_cart;
std::array<string, 4> wanted_goods;
string good;
int gd_counter=0;
int wd_counter=0;
cout << "welcome to my shopping list, tap A to cont. and B to quit!" << endl;
cin >> x;
while (x == 'A' || x == 'B'){
if(x == 'B'){
break;
}
else {
cout << "Type the name of the item!" << endl;
cin >> good;
if (std::find(supplies.begin(), supplies.end(), good) != supplies.end()) {
shopping_cart[gd_counter++] = good;
cout << "we have that item!" << endl;
} else {
wanted_goods[wd_counter++] = good;
cout << "we do not have that item!" << endl;
}
if (gd_counter < shopping_cart.size()
&& wd_counter < wanted_goods.size()) {
cout << "do you want to complete!?" << endl;
cin >> x;
} else {
cout << "you can't add more items!" << endl;
break;
}
}
}
cout << "shopping card:" << endl;
for(int z=0; z<gd_counter; z++){
cout << shopping_cart[z] << endl; // print out what the user has found in my shopping list
}
cout << "wanted goods:" << endl;
for(int c=0; c<wd_counter; c++){
cout << wanted_goods[c] << endl; // print out the items that the user has not found it
}
}
为什么0.3出来而不是0.30000000000000004?
答案 0 :(得分:5)
这是因为当你打印它时(例如使用fmt
包),打印功能已经四舍五入到一定数量的小数位。
见这个例子:
const ca, cb = 0.1, 0.2
fmt.Println(ca + cb)
fmt.Printf("%.20f\n", ca+cb)
var a, b float64 = 0.1, 0.2
fmt.Println(a + b)
fmt.Printf("%.20f\n", a+b)
输出(在Go Playground上尝试):
0.3
0.29999999999999998890
0.30000000000000004
0.30000000000000004441
首先我们使用了constants,因为它与使用float64
类型的(非常量)值不同。 数字常量表示任意精度的精确值,不会溢出。
但是在打印ca+cb
的结果时,必须将常量值转换为非常量的类型值,以便能够传递给fmt.Println()
。此值的类型为float64
,不能完全代表0.3
。但fmt.Println()
会将其四舍五入到约16个小数位,即0.3
。但是当我们明确说明我们希望它显示20位数字时,我们会发现它并不准确。请注意,只有0.3
将转换为float64
,因为编译器将在编译时评估常量算术0.1+0.2
。
接下来我们开始使用float64
类型的变量,毫不奇怪,输出完全没有0.3
,但这次即使使用默认舍入,我们得到的结果也不同于{{ 1}}。这是因为在第一种情况下(常量)转换了0.3
,但这次0.3
和0.1
都转换为0.2
,没有这是确切的,并添加它们导致一个数字与float64
的距离更大,足以形成一个&#34;视觉外观&#34;使用0.3
包的默认舍入。
查看类似/相关问题+答案,了解有关该主题的更多信息:
Why do these two float64s have different values?
How does Go perform arithmetic on constants?
Golang converting float64 to int error
Does go compiler's evaluation differ for constant expression and other expression