没有精度的双值减法
double value subtraction without precision
int base = 12;
double number = 12.2112;
double c = number - base;
//// c=0.211199999999999983
这是 C++ 代码,
我怎么能得到结果:c=0.2112,
0.2112 无法用浮点表示法准确表示:https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
如果准确表示 0.2112 对您来说极其重要,那么通常的解决方案看起来有点像这样:
int base = 120000;
int number = 122112;
int c = number - base;
cout << "Value of c: " << (c / 10000.0) << endl;
但是请注意,我们在这里所做的是实现定点数。如果您在实现中需要定点数,可能值得研究和实现一个完整的定点数 class,它可以完成您在这里想要完成的所有事情。
int base = 12;
double number = 12.2112;
double c = number - base;
//// c=0.211199999999999983
这是 C++ 代码, 我怎么能得到结果:c=0.2112,
0.2112 无法用浮点表示法准确表示:https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
如果准确表示 0.2112 对您来说极其重要,那么通常的解决方案看起来有点像这样:
int base = 120000;
int number = 122112;
int c = number - base;
cout << "Value of c: " << (c / 10000.0) << endl;
但是请注意,我们在这里所做的是实现定点数。如果您在实现中需要定点数,可能值得研究和实现一个完整的定点数 class,它可以完成您在这里想要完成的所有事情。