2013-03-13 359 views
2

我收到此錯誤, 我寫了這樣的代碼下面如何解決在c#中試圖除以零?

代碼:

decimal Amnt; 
decimal.TryParse(txtAmnt.Text, out Amnt); 
int tnure=1; 
int.TryParse(txtTnre.Text, out tnure); 
txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00"); 

當文本框的值0我得到這個error.If有可能給予的回答我。

+3

你是什麼意思「解決」?在分割之前驗證值,或者處理異常,如果驗證不是此處的選項。我希望,你不想找到一個如何允許除以零的方法。 – Dennis 2013-03-13 05:28:24

+0

在分割操作發生之前檢查'tnure!= 0'值。 – asitis 2013-03-13 05:40:23

回答

6

越來越鴻溝如何簡單地使用if被零除前檢查?

if(tnure != 0) 
    txtDdctAmnt.Text = (Amnt/tnure).ToString("0.00"); 
else 
    txtDdctAmnt.Text = "Invalid value"; 
3

檢查tnure不爲0,你是零異常,更多的幫助,在http://msdn.microsoft.com/en-us/library/ms173160.aspx

decimal Amnt; 
     decimal.TryParse(txtAmnt.Text, out Amnt); 
     int tnure=1; 
     int.TryParse(txtTnre.Text, out tnure); 
if(tnure!=0) 
{ 
     txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00"); 
} 
else 
{ 
/*handle condition*/ 
} 
+0

謝謝,我試過它正在得到正確的答案 – user1899761 2013-03-13 05:49:28

0

代碼放在try/catch語句這樣

try 
    { 
    decimal Amnt; 
    decimal.TryParse(txtAmnt.Text, out Amnt); 
    int tnure=1; 
    int.TryParse(txtTnre.Text, out tnure); 
    txtDdctAmnt.Text = (Amnt /tnure).ToString("0.00"); 
    } 
    catch(Exception ex) 
    { 
     // handle exception here 
     Response.Write("Could not divide any number by 0"); 
    } 
+1

爲什麼你要等待例外?你不能檢查嗎?並且永遠不會捕獲全局的'Exception'異常。 – gdoron 2013-03-13 05:33:09

1

當tnre爲0,Amnt /tnure是0師,您需要檢查tnre是否爲0分前,和唐」如果它等於0,則除以tnre。