C# 可能的分数损失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1061334/
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-06 07:17:29  来源:igfitidea点击:

Possible Loss of Fraction

c#math

提问by CodeLikeBeaker

Forgive me if this is a na?ve question, however I am at a loss today.

如果这是一个天真的问题,请原谅我,但是我今天不知所措。

I have a simple division calculation such as follows:

我有一个简单的除法计算,如下所示:

double returnValue = (myObject.Value / 10);

Value is an int in the object.

值是对象中的一个整数。

I am getting a message that says Possible Loss of Fraction. However, when I change the double to an int, the message goes away.

我收到一条消息,上面写着可能的分数丢失。但是,当我将 double 更改为 int 时,消息消失了。

Any thoughts on why this would happen?

关于为什么会发生这种情况的任何想法?

采纳答案by ólafur Waage

When you divide two int's into a floating point value the fraction portion is lost. If you cast one of the items to a float, you won't get this error.

当您将两个 int 划分为一个浮点值时,小数部分会丢失。如果将其中一项转换为浮点数,则不会出现此错误。

So for example turn 10 into a 10.0

因此,例如将 10 变成 10.0

double returnValue = (myObject.Value / 10.0);

回答by segfault

I think since myObject is an int, you should

我认为既然 myObject 是一个 int,你应该

double returnValue=(myObject.Value/10.0); 

回答by lc.

You're doing integer division if myObject.Valueis an int, since both sides of the /are of integer type.

如果myObject.Value是 int,你正在做整数除法,因为两边/都是整数类型。

To do floating-point division, one of the numbers in the expression must be of floating-point type. That would be true if myObject.Value were a double, or any of the following:

要进行浮点除法,表达式中的数字之一必须是浮点类型。如果 myObject.Value 是双精度值或以下任一值,则为真:

double returnValue = myObject.Value / 10.0;
double returnValue = myObject.Value / 10d; //"d" is the double suffix
double returnValue = (double)myObject.Value / 10;
double returnValue = myObject.Value / (double)10;

回答by Cambium

An integer divided by an integer will return your an integer. Cast either Value to a double or divide by 10.0.

一个整数除以一个整数将返回一个整数。将 Value 转换为 double 或除以 10.0。

回答by paxdiablo

Assuming that myObject.Valueis an int, the equation myObject.Value / 10will be an integer division which will then be cast to a double.

假设它myObject.Valueint,方程myObject.Value / 10将是一个整数除法,然后将被转换为双精度。

That means that myObject.Value being 12 will result in returnValue becoming 1, not1.2.

这意味着 myObject.Value 为 12 将导致 returnValue 变为 1,而不是1.2。

You need to cast the value(s) first:

您需要先转换值:

double returnValue = (double)(myObject.Value) / 10.0;

This would result in the correct value 1.2, at least as correct as doubles will allow given their limitations but that's discussed elsewhere on SO, almost endlessly :-).

这将导致正确的值 1.2,至少与考虑到双打的局限性一样正确,但这在 SO 的其他地方几乎无休止地讨论过:-)。