C#错误的减法? 12.345 - 12 = 0.345000000000001 [英] C# wrong subtraction? 12.345 - 12 = 0.345000000000001
本文介绍了C#错误的减法? 12.345 - 12 = 0.345000000000001的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
解决方案
考虑使用十进制而不是浮点数:
//而不是这个...
float a = 12.345F;
float b = 12;
float c = a - b;
//使用这个:
十进制d = 12.345M;
十进制e = 12;
十进制f = d - e;
Jon Skeet在这个答案中对两种类型的区别给出了很好的解释:https://stackoverflow.com/a/618596/446681
I am beginner in C# and I am working with floating point numbers. I need to do subtraction between these two numbers but it does not work. I know it is caused by floating point number, but how can I fix it please and if you be so good can you explain me why is it happening? Thanks in advance.
解决方案
Consider using decimal instead of float:
// Instead of this...
float a = 12.345F;
float b = 12;
float c = a - b;
// Use this:
decimal d = 12.345M;
decimal e = 12;
decimal f = d - e;
Jon Skeet gives a good explanation of the differences between both types in this answer: https://stackoverflow.com/a/618596/446681
这篇关于C#错误的减法? 12.345 - 12 = 0.345000000000001的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文