除法功能不会除法.它总是返回零.为什么?这是什么废话?
问题描述:
您知道overload/order
部分返回的内容吗? 0.
在调试器中,它甚至列出了overload = 1
和order = 5
和overload / order = 0
.请说明问题所在.
Do you know what the overload/order
part returns? 0.
In the debugger, it even listed overload = 1
and order = 5
and overload / order = 0
. Explain what the problem is.
public void Progress(int overload)
{
progressBar.Value = ((overload / order) * 100);
}
答
—SA
—SA
如果您尝试执行以下操作,int intAsFloat = 0.2;
,然后编译器会抱怨.要解决此问题,我们需要将intAsFloat变量的数据类型从int
更改为float
(例如).
在您的示例代码overload
和(我假设)order
中也将int用作整数,当您将1/5除以1时,它将产生0.2,并尝试将结果存储为0,然后乘以100,最后得到0.可以在下面尝试,
If you try to do something like below,int intAsFloat = 0.2;
then compiler will complain. To solve the issue we need to change the data type of intAsFloat variable fromint
tofloat
(for example).
In your example codeoverload
and (I assume)order
also as int and when you divide 1/5 then it produce 0.2 and try to store that result with value 0 and then multiply by 100 and eventually you get 0. you could try below,
public static void Progress(float overload, float order)
{
var result = ((overload / order) * 100);
}
希望对您有所帮助:)
hope it helps :)
这不是很明显吗?用整数除法可以完美地解释您的结果.
顺便说一句,如果您先乘以倍数,您将有更多的运气:
Isn''t it obvious? Your result is perfectly explained by integer division.
By the way, you would have much more luck if you multiply first:
int result = 100 * overload / order;
更好的是,始终使用浮点数,但只有在屏幕上显示结果时才将其舍入为整数:
Better yet, work with floating point number all the time but round it to integer only when you show the result on screen:
double result = 100d * overload / order;
int uiResult = (int)System.Math.Round(result);