Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my "Divide by Zero" prevention not working? [closed]

Tags:

c#

I've been working on a calculator using C# and came across an issue I haven't been able to work past.

Currently when a user enters a number divided by zero then the answer defaults to 0.00 when instead it should be invalid.

I have no idea why and after tinkering with it for awhile I haven't been able to figure it out. Here is the relevant code:

private void button1_Click(object sender, EventArgs e)
{
                double number1, number2, ans; // Identify variables as double to account for decimals.
                number1 = Convert.ToDouble(num1.Text); // Convert the contents of the textBox into a double.
                number2 = Convert.ToDouble(num2.Text); // 
                ans = 0.0;
                string symbol = modifier1.Text;

                if (symbol == "/" && number2 == 0) // This part seems to be broken.
                    answer.Text = "Invalid input.";
                else
                    if (symbol == "+")
                        ans = number1 + number2;
                    else if (symbol == "-")
                        ans = number1 - number2;
                    else if (symbol == "/")
                        ans = number1 / number2;
                    else if (symbol == "*")
                        ans = number1 * number2;
                    else
                        ans = 0;

                    answer.Text = ans.ToString("n"); // Change label value to a number.
}

Does anyone have any ideas on how I can fix this? It seems pretty straight forward but I'm missing something.

like image 830
Vale Avatar asked Jul 17 '15 06:07

Vale


People also ask

How do you fix divide by zero error encountered?

We can avoid this error message using the following three methods: Using NULLIF() function. Using CASE statement. Using SET ARITHABORT OFF.

What error is division by zero?

Microsoft Excel shows the #DIV/0! error when a number is divided by zero (0). It happens when you enter a simple formula like =5/0, or when a formula refers to a cell that has 0 or is blank, as shown in this picture.

Is divide by zero A interrupt or trap?

CPUs tend to throw an exception interrupt, on things like division by zero, or dereferencing a NULL pointer. These interrupts are trapped, like when hardware interrupts, halting execution of current program and return control to the OS, which then handles the event.


2 Answers

Change this :

if (symbol == "/" && number2 == 0) // This part seems to be broken.
                answer.Text = "Invalid input.";

To :

if (symbol == "/" && number2 == 0) { answer.Text = "Invalid input."; return; }

Explanation: The condition in 'if' clause in your code is correct. And it does what is expected - it changes answer.Text property to "Invalid input" however a bit later it is changed again on this line :

answer.Text = ans.ToString("n"); // Change label value to a number.

And because your condition in 'if' clause returned true - 'else' block was not executed. That's why you see 0.00 (default value of type double).

P.S. So by adding return statement to if clause you just basically end your method. It is like if you say to compiler *"Hey if this guy is trying to divide by zero alert him 'Ivalid input' and do nothing, return from method".*

Other way to sort it out would be to :

if (divide by zero attempt) { your code here } else
{
    and place rest of your method code here
}

But I would not recommend this because it uses redundant else statement and {} figures. You can avoid all of it by using if() {....; return; } in your case.

You may also benefit from using switch block and your code might be refactored to something like :

double number1, number2, ans; // Identify variables as double to account for decimals.
number1 = Convert.ToDouble(num1.Text); // Convert the contents of the textBox into a double.
number2 = Convert.ToDouble(num2.Text); // 
ans = 0.0;
string symbol = modifier1.Text;

if (symbol == "/" && number2 == 0) { answer.Text = "Invalid input."; return;}
switch(symbol)
{
   case "+": ans = number1 + number2; break;
   case "-": ans = number1 - number2; break;
   case "*": ans = number1 * number2; break;
   case "/": ans = number1 / number2; break;
   default : answer.Text = "Invalid sign."; return;
}                

answer.Text = ans.ToString("n"); // Change label value to a number.
like image 146
Fabjan Avatar answered Oct 19 '22 03:10

Fabjan


To help you understand what's gone wrong, it helps to lay the code out as the compiler sees it, rather than how you imagine it's working:

double number1, number2, ans; // Identify variables as double to account for decimals.
number1 = Convert.ToDouble(num1.Text); // Convert the contents of the textBox into a double.
number2 = Convert.ToDouble(num2.Text); // 
ans = 0.0;
string symbol = modifier1.Text;

if (symbol == "/" && number2 == 0) // This part seems to be broken.
    answer.Text = "Invalid input.";
else if (symbol == "+")
    ans = number1 + number2;
else if (symbol == "-")
    ans = number1 - number2;
else if (symbol == "/")
    ans = number1 / number2;
else if (symbol == "*")
    ans = number1 * number2;
else
    ans = 0;

answer.Text = ans.ToString("n"); // Change label value to a number.

So when the divide by zero situation occurs, first answer.Text is set to "Invalid input.", then the control flow drops to the last line and it's overwritten with 0.0.

The neatly highlights why it's really important to use {} even for single statements. Do that and the code will work as you expect:

double number1, number2, ans; // Identify variables as double to account for decimals.
number1 = Convert.ToDouble(num1.Text); // Convert the contents of the textBox into a double.
number2 = Convert.ToDouble(num2.Text); // 
ans = 0.0;
string symbol = modifier1.Text;

if (symbol == "/" && number2 == 0) // This part seems to be broken.
{
    answer.Text = "Invalid input.";
}
else 
{
    if (symbol == "+")
    {
        ans = number1 + number2;
    }
    else if (symbol == "-")
    {
        ans = number1 - number2;
    }
    else if (symbol == "/")
    {
        ans = number1 / number2;
    }
    else if (symbol == "*")
    {
        ans = number1 * number2;
    }
    else
    {
        ans = 0;
    }

    answer.Text = ans.ToString("n"); // Change label value to a number.
}
like image 5
David Arno Avatar answered Oct 19 '22 01:10

David Arno