How do I allow dividing by zero?

时间:2017-06-15 10:10:04

标签: c#

I'm trying to make a lillte C# application that will calcualte how much school work you've done.

     calc1 = totalIp / totalPidl;
        percentageBox.Text = percbox;
        percbox = calc1.ToString();

the error happens at calc1 = totalip / totalPidl; there are no typos or anything else. how can i allow dividing by zero?

Thanks.

6 个答案:

答案 0 :(得分:3)

That's mathematically impossible.

Prevent division by zero by code:

if(totalPidl == 0.0)
{
  percentageBox.Text = "???";
}
else
{   
  calc1 = totalIp / totalPidl;
  percentageBox.Text = calc1.ToString();
}

答案 1 :(得分:1)

It is not a good idea to allow division by zero. What value do you want? does it make sense? It is better to do something like this:

calc1 = totalPidl != 0 ? totalIp / totalPidl : 0; // I assume you want the result to be 0

答案 2 :(得分:0)

Why would you allow a division by zero? Give a try catch block with specified output to display "No work done" if the division by zero is going to happen. Read this for better understanding

答案 3 :(得分:0)

Dividing by zero does not give a valid mathematical result. To avoid the exception you can use a ternary operator that will return 0 when totalPidl is 0:

calc1 = totalPidl != 0 ? totalIp / totalPidl : 0;

答案 4 :(得分:0)

As i can understand you want to have 0 result if you have 0 denominator. So you can use ternary if operator:

calc1 = totalPidl == 0 ? 0: totalIp / totalPidl;

答案 5 :(得分:0)

You can't avoid DivideByZeroException. You can ignore it by catching the exception or have a condition and check for 0 before doing the calculation

calc1 = 0;
try
{
   calc1 = totalIp / totalPidl;
}
finally
{
    percentageBox.Text = percbox;
    percbox = calc1.ToString();
}

Or

if(totalIp != 0)
{
   calc1 = totalIp / totalPidl;
}
percentageBox.Text = percbox;
percbox = calc1.ToString();