在C#中使除法返回两倍的最佳实践是什么 [英] What is the best practice to make division return double in C#
问题描述
在c#中,当您想对以下方法的结果进行除法时,最好的方法是强制其返回双精度值而不是默认整数.
In c# when you want to divide the result of a method such as below, what is the best way to force it to return a double value rather than the default integer.
(int)Math.Ceiling((double)(System.DateTime.DaysInMonth(2009, 1) / 7));
如您所见,我需要除法返回双精度数,以便可以使用吊顶函数.
As you can see I need the division to return a double so I can use the ceiling function.
推荐答案
两个 int
数字的除法将返回一个 int
,将所有小数点都截断.通常,其他数据类型也是如此:算术运算不会更改其操作数的类型.
A division of two int
numbers returns an int
, truncating any decimal points. This is generally true for other data types as well: arithmetic operations don't change the type of their operands.
要强制执行某种返回类型,因此必须适当地转换操作数.在您的特定情况下,将其中一个运算符转换为 double
实际上就足够了:这样,C#将自动为另一个操作数执行转换.
To enforce a certain return type, you must therefore convert the operands appropriately. In your particular case, it's actually sufficient to convert one of the operators to double
: that way, C# will perform the conversion for the other operand automatically.
您可以选择:可以显式转换任何一个操作数.但是,由于第二个操作数是 literal ,最好直接将其设为正确的类型.
You've got the choice: You can explicitly convert either operand. However, since the second operand is a literal, it's better just to make that literal the correct type directly.
这可以使用类型后缀(在 double
的情况下为 d
)完成,也可以在其后写一个小数点.通常优选后一种方式.在您的情况下:
This can either be done using a type suffix (d
in the case of double
) or to write a decimal point behind it. The latter way is generally preferred. in your case:
(int)Math.Ceiling(System.DateTime.DaysInMonth(2009, 1) / 7.0);
请注意,此小数点表示法始终会产生 double
.要制作 float
,您需要使用其类型后缀: 7f
.
Notice that this decimal point notation always yields a double
. To make a float
, you need to use its type suffix: 7f
.
顺便说一下,基本运算符的这种行为对于几乎所有语言都相同.一个值得注意的例外:VB,除法运算符通常产生 Double
.如果不需要这种转换,则有一个特殊的整数除法运算符( \
).C ++的另一个例外是一种怪异的方式:两个相同类型的指针之间的区别是 ptrdiff_t
.这是有道理的,但它打破了一个模式,即运算符总是产生与其操作数相同的类型.特别是,减去两个 unsigned int
不会 not 产生一个 signed int
.
This behaviour of the fundamental operators is the same for nearly all languages out there, by the way. One notable exception: VB, where the division operator generally yields a Double
. There's a special integer division operator (\
) if that conversion is not desired. Another exception concerns C++ in a weird way: the difference between two pointers of the same type is a ptrdiff_t
. This makes sense but it breaks the schema that an operator always yields the same type as its operands. In particular, subtracting two unsigned int
does not yield a signed int
.
这篇关于在C#中使除法返回两倍的最佳实践是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!