C# 新手,当下面的 int 'max' 为 0 时,我得到除以零的错误,我可以明白为什么会发生这种情况,但是当 max 为 0 时我应该如何处理这个问题?位置也是一个整数。
private void SetProgressBar(string text, int position, int max)
{
try
{
int percent = (100 * position) / max; //when max is 0 bug hits
string txt = text + String.Format(". {0}%", percent);
SetStatus(txt);
}
catch
{
}
}
int percent = 0
if (max != 0) percent = (100*position) / max
嗯,这完全取决于您想要的行为。如果你的程序栏的最大值为零,它是否已满?是空的吗?这是一个设计选择,当您选择后,只需测试 max == 0 并部署您的答案。
int percent = ( max > 0 ) ? (100 * position) / max : 0;
取决于你想要什么。
检查零。
if ( max == 0 ) {
txt = "0%";
} else {
// Do the other stuff....
这不是一个 C# 问题,这是一个数学问题。除以零是未定义的。有一个 if 语句来检查 max 是否> 0,然后只执行除法。
转换你的
int percent = (100 * position) / max;
进入
int percent;
if (max != 0)
percent = (100 * position) / max;
else
percent = 100; // or whatever fits your needs
好吧,如果 max 为零,那么就没有进展。尝试捕获调用此函数的异常。这可能是决定是否存在问题或进度条是否应设置为零或 100% 的地方。
我想根本问题是:在 max 为“0”的情况下调用这个函数是否有意义?如果是,那么我会对其添加特殊处理,即:
if (max == 0)
{
//do special handling here
}
else
{
//do normal code here
}
如果 0 没有意义,我会调查它来自哪里。
您需要一个保护子句来检查 max == 0。
private void SetProgressBar(string text, int position, int max)
{
if(max == 0)
return;
int percent = (100 * position) / max; //when max is 0 bug hits
string txt = text + String.Format(". {0}%", percent);
SetStatus(txt);
}
您还可以处理除以零异常,如示例所示,但处理异常通常比设置已知错误值的检查成本更高。
如果您使用它进行下载,您可能希望显示 0%,因为我假设在这种情况下,当您还不知道文件大小时 max == 0。
int percent = 0;
if (max != 0)
...;
如果您将其用于其他一些长期任务,我想假设 100%
但是,由于位置永远不能介于 0 和 -1 之间,因此您可能需要删除 100 *
您可以使用三元运算符。
int percent = max != 0 ? (100 * position) / max : 0;
这意味着当max不等于0时,执行计算。如果等于 0,则将百分比设置为 0。
这对我有用:
var percent = (paid + 1) / (total + 10);