四舍五入C#给出错误的答案 [英] Rounding up c# giving wrong answer

查看:98
本文介绍了四舍五入C#给出错误的答案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个学校项目(自行车工厂)编程一个库存/生产程序,并且我必须对一些数字进行汇总,例如必须生产的自行车(由于辐射的影响,它是双倍的).

I am programming a stocks/production program for a school project (bike factory) and I have to round some numbers up such as the bikes that have to be produced (due to fallout it are doubles).

如果我使用以下代码:

double test = Math.Ceiling(100 * 1.09);

label75.Text = Convert.ToString(test);

我的回答是110,但这不对,应该是109(100%的9%).尽管它似乎适用于低于9%的值.

I get as an answer 110, but that's not right, it should be 109 (9% of 100). Although it seems to work with values below 9%.

我在做什么错了?

推荐答案

double s和float s是二进制浮点类型.这意味着它们不能精确表示许多十进制数字(如1.09).这会导致一些微妙的舍入错误.在您的情况下,100 * 1.09实际上产生的数字比109大得多,因此Ceiling函数正确地将其四舍五入为最接近的整数110.

doubles and floats are binary floating point types. This means they cannot precisely represent many decimal numbers (like 1.09). This leads to some subtle round off errors. In your case 100 * 1.09 actually results in a number very slightly larger than 109, so the Ceiling function correctly rounds it up to the nearest integer, 110.

将其更改为decimal,您将获得预期的结果:

Change it to a decimal and you'll get the result you expect:

decimal test = Math.Ceiling(100 * 1.09m); // 109

请注意,1.09m中的m将其标识为decimal文字.之所以可行,是因为decimal类型专门用于表示十进制数字(而不是像doublefloat那样只是二进制近似值).

Note the m in 1.09m identifies it as a decimal literal. This works because the decimal type is specifically designed to represent decimal numbers (rather than just their binary approximations, as double and float do).

这篇关于四舍五入C#给出错误的答案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆