简体   繁体   English

Math.Round 十进制数

[英]Math.Round for a decimal number

Code:代码:

double PagesCount = 9 / 6 ;
Console.WriteLine(Math.Round(PagesCount, 0));

I'm trying to round the answer to 9/6(1,5) to 2 but this code snippet always results in 1. How can I avoid that?我试图将 9/6(1,5) 的答案四舍五入到 2,但此代码片段总是导致 1。我该如何避免这种情况?

9 / 6 is an integer division which returns an integer, which is then cast to a double in your code. 9 / 6是一个整数除法,它返回一个整数,然后在您的代码中将其转换为双精度数。

To get double division behavior, try要获得双除行为,请尝试

double PagesCount = 9d / 6 ;
Console.WriteLine(Math.Round(PagesCount, 0));

(BTW I'm picky but decimal in the .net world refers base 10 numbers, unlike the base 2 numbers in your code) (顺便说一句,我很挑剔,但 .net 世界中的十进制是指以 10 为基数的数字,与代码中的以 2 为基数的数字不同)

Math.Round is not the problem here. Math.Round不是这里的问题。

9.0 / 6.0 ==> 1.5 but 9 / 6 ==> 1 because in the second case an integer division is performed. 9.0 / 6.0 ==> 1.59 / 6 ==> 1因为在第二种情况下执行整数除法。

In the mixed cases 9.0 / 6 and 9 / 6.0 , the int is converted to double and a double division is performed.在混合情况9.0 / 69 / 6.0int被转换为double并执行double除法。 If the numbers are given as int variables, this means that is enough to convert one of them to double :如果数字作为int变量给出,这意味着足以将其中之一转换为double

(double)i / j ==> 1.5

Note that the integer division is complemented by the modulo operator % which yields the remainder of this division:请注意,整数除法由模运算符%补充,产生该除法的余数:

9 / 6 ==> 1
9 % 6 ==> 3

because 6 * 1 + 3 ==> 9因为6 * 1 + 3 ==> 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM