2015-07-17 26 views
5

Pracowałem nad kalkulatorem przy użyciu C# i natknąłem się na problem, z którym nie mogłem pracować.Dlaczego moje zapobieganie "Podziel przez zero" nie działa?

Obecnie, gdy użytkownik wprowadza liczbę podzieloną przez zero, domyślna wartość odpowiedzi wynosi 0,00, zamiast tego powinna być nieważna.

Nie mam pojęcia, dlaczego i po majstrowaniu przy nim przez chwilę nie byłem w stanie tego rozgryźć. Oto odpowiedni kod:

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. 
} 

Czy ktoś ma jakieś pomysły, jak mogę to naprawić? Wydaje się to całkiem proste, ale czegoś mi brakuje.

+8

brakuje 'return' lub nawiasy klamrowe. Proszę użyć debuggera, aby potwierdzić. Upewnij się również, że znasz zasady używania języka - C# * nie * używa znaczących białych znaków w przeciwieństwie do innych języków. –

Odpowiedz

12

Zmień to:

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

Do:

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

Objaśnienie: Warunek w klauzuli 'if' w kodzie jest poprawna. I robi to co należy oczekiwać - zmienia właściwość answer.Text do „Invalid input” jednak nieco później jego zmiany na tej linii:

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

a ponieważ stan w „if” klauzula powrócił prawda - ' blok else nie został wykonany. Dlatego widzisz 0.00 (domyślna wartość typu double).

P.S. Tak więc dodając instrukcję return do klauzuli if po prostu kończysz swoją metodę. To tak jakby powiedzieć, aby kompilator * „Hej jeśli ten facet stara się divide by zero ostrzec go«wejściowy Ivalid»i nic nie robić, powrót z metody”. *

Inny sposób rozwiązać to byłoby :

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

Ale nie poleciłbym tego, ponieważ używa redundantnej instrukcji else i {} liczb. Możesz tego uniknąć, używając if() {....; powrót; } w Twoim przypadku.

Można również skorzystać z systemu switch bloku i kod może być refactored do czegoś podobnego:

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. 
+2

@ Sayse Dziękuję. Wyjaśniłem to w mojej aktualizacji odpowiedzi. – Fabjan

+0

@DavidArno Instrukcja Else w kodzie operacji jest poprawna, ponieważ ma tylko JEDNĄ klauzulę if i nic więcej. W ten sposób: else if (symbol == "+") // jakiś kod // else if i tak dalej. Sprawdź, czy moja aktualizacja odpowiedzi wyjaśnia wszystko. – Fabjan

4

Aby pomóc Ci zrozumieć, co poszło nie tak, to pomaga położyć kod jako kompilator widzi, zamiast, jak można sobie wyobrazić, że to działa:

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. 

Więc kiedy występuje dzielenie przez zero sytuacji, najpierw answer.Text jest ustawiony na „Nieprawidłowe dane wejściowe.”, a następnie przepływ sterowania spadnie do ostatniej linii i to nadpisane 0.0.

Podkreśla, dlaczego tak ważne jest używanie {} nawet do pojedynczych instrukcji.Zrobić i kod będzie działać zgodnie z oczekiwaniami:

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. 
} 
+0

Doskonałe wyjaśnienie, dziękuję! – ArnoldM904

Powiązane problemy