gpt4 book ai didi

Dividing Math with C#(用C#实现数学分割法)

转载 作者:bug小助手 更新时间:2023-10-24 17:54:49 25 4
gpt4 key购买 nike



This has a potentially simple answer but I can't figure it out -

这可能有一个简单的答案,但我想不出来-



double Result = 1 / 12;


returns 0, while

返回0,而



double Result2 = 24 / 12;


return 2

返回2



What's going on and how can I fix it?

这是怎么回事,我怎么才能修好呢?


更多回答

use decimal instead of double? msdn.microsoft.com/en-us/library/678hzkk9(v=vs.71).aspx

用十进制而不是双精度?Msdn.microsoft.com/en-us/library/678hzkk9(v=vs.71).aspx

Why is this getting downvotes? Perfectly valid question for someone new or not-so-experienced to programming.

为什么这会得到反对票呢?对于编程新手或不是很有经验的人来说,这是一个非常合理的问题。

优秀答案推荐

Try this:

试试这个:



double Result = 1 / (double)12;


or this:

或者这样:



double Result = 1 / 12D;


In C# (and also in a lot of other languages), integer division returns an integer. By casting one of the operands to double or explicitly declaring a literal double you can force the division expression to return a double and not truncate after the decimal place.

在C#中(以及在许多其他语言中),整数除法返回一个整数。通过将一个操作数强制转换为DOUBLE或显式声明文字双精度值,可以强制除法表达式返回双精度值,并且不在小数位后截断。



it is doing integer math because the numbers on the right are evaluated as integers.

它正在进行整数运算,因为右侧的数字被计算为整数。



try 1.0/12;

尝试1.0/12;



this will work too

这也会奏效的



Decimal.Divide(1, 12)


It has a result with higher precision, but a smaller range.

它的结果精度更高,但范围更小。



The problem is that 1 and 12 are integers (of type int, not double). This means the values ignore anything past the decimal point. When you divide 1 by 12, you get 0.083. Since anything past the decimal point is truncated for int, you are left with 0.

问题是1和12是整数(类型为int,不是Double)。这意味着这些值忽略小数点以外的任何内容。当你用1除以12时,得到0.083。由于任何超过小数点的值都会被截断为int,因此只剩下0。



To get expected results, one of your operands needs to be of type double. You can do this by changing 1 to 1.0 or 12 to 12.0 (or both, as long as at least one of the operands is a double).

要获得预期的结果,您的一个操作数需要是Double类型。可以通过将1更改为1.0或将12更改为12.0(或同时将这两个更改为1.0,只要至少有一个操作数为双精度)。



I think you need to cast your values

我认为你需要改变你的价值观



double Result = (double)1 / (double)12


has something to do with integer based math always returns an integer.....

与基于整数的数学有关,总是返回整数.....


更多回答

Just to add, the integer division will truncate the decimal value, not round to the nearest value. So 5/3 = 1 and -5/3 = -1 and not 2 or -2 as expected from normal rounding.

只是为了增加,整数除法将截断十进制值,而不是四舍五入到最近的值。因此,5/3 = 1和-5/3 = -1,而不是正常舍入所期望的2或-2。

@AustinSalonen: that's what I said. I just figured it'd be worthwhile for William to know.

@AustinSalonen:我就是这么说的。我只是觉得威廉知道这件事是值得的。

Casting only one of them will also do.

只选其中一位也行。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com