在 C# 中除法以获得精确值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15400903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:40:50  来源:igfitidea点击:

Division in C# to get exact value

c#floating-pointinteger-division

提问by Irannabi

If I divide 150 by 100, I should get 1.5. But I am getting 1.0 when I divided like I did below:

如果我将 150 除以 100,我应该得到 1.5。但是当我像下面那样划分时,我得到了 1.0:

double result = 150 / 100;

Can anyone tell me how to get 1.5?

谁能告诉我如何获得1.5?

回答by Aniket Inge

double result = (150.0/100.0)

One or both numbers should be a float/double on the right hand side of =

一个或两个数字应该是右侧的浮点数/双精度数 =

回答by MattW

Cast one of the ints to a floating point type. You should look into the difference between decimal and double and decide which you want, but to use double:

将其中一个整数转换为浮点类型。您应该研究十进制和双精度之间的区别并决定您想要哪个,但要使用双精度:

double result = (double)150 / 100;

回答by Mayank

Make the number float

做号码 float

var result = 150/100f

or you can make any of number to float by adding .0:

或者您可以通过添加.0以下内容使任何数字浮动:

double result=150.0/100

or

或者

double result=150/100.0

回答by Heinrich

try:

尝试:

 double result = (double)150/100;

When you are performing the division as before:

当您像以前一样执行除法时:

double result = 150/100;

The devision is first done as an Int and then it gets cast as a double hence you get 1.0, you need to have a double in the equation for it to divide as a double.

该除法首先作为一个 Int 完成,然后它被转换为一个双精度数,因此您得到 1.0,您需要在等式中有一个双精度数才能将其除为双精度数。

回答by Jason Whitish

If you're just using literal values like 150 and 100, C# is going to treat them as integers, and integer math always "rounds down". You can add a flag like "f" for float or "m" for decimal to not get integer math. So for example result = 150m/100mwill give you a different answer than result = 150/100.

如果你只是使用像 150 和 100 这样的字面值,C# 会将它们视为整数,并且整数数学总是“四舍五入”。您可以为浮点数添加“f”之类的标志,或为十进制添加“m”之类的标志,以免获得整数数学。因此,例如result = 150m/100m会给你一个不同的答案result = 150/100