2016-12-16 42 views
1

我想使用只有文本框來做一個簡單的計算器。 我以爲我的代碼是正確的,但結果幾乎總是錯的。只使用文本框操作c#

這是代碼:

void TextBoxPercorsoTextChanged(object sender, EventArgs e) 
    { 
     if(!string.IsNullOrEmpty(textBoxPercorso.Text) && !string.IsNullOrEmpty(textBoxAgilitySmallVelocita.Text)) 
      textBoxAgilitySmallTps.Text=(Convert.ToDecimal(textBoxPercorso.Text)/Convert.ToDecimal(textBoxAgilitySmallVelocita.Text)).ToString(); 
    } 

    void TextBoxAgilitySmallVelocitaTextChanged(object sender, EventArgs e) 
    { 
     if(!string.IsNullOrEmpty(textBoxPercorso.Text) && !string.IsNullOrEmpty(textBoxAgilitySmallVelocita.Text)) 
      textBoxAgilitySmallTps.Text=(Convert.ToDecimal(textBoxPercorso.Text)/Convert.ToDecimal(textBoxAgilitySmallVelocita.Text)).ToString(); 
    } 

我試圖做一些嘗試。例如,我試圖做10/5,但結果是0.5。只有10月份的結果是正確的。

你能幫助我嗎?

+9

難道是你需要顛倒你的論點嗎? – npinti

+0

@npinti你是對的!但我不明白爲什麼。我必須做長度/速度,所以我做了textboxLength/textboxSpeed。如果我顛倒了我的論點,結果是正確的 – Marietto

+0

請確保您沒有交換顯示屏上的文本框,因此當您正在考慮您正在閱讀另一個字段時,您將從一個字段中讀取。 – npinti

回答

0

嘗試迴避魔法按鈕 antipattern(提取方法);不要重複自己(複製+粘貼):

private void ComputeSmallTps() { 
    decimal perCorso; 
    decimal smallVelocita; 

    // first, parse arguments... 
    if (!decimal.TryParse(textBoxPercorso.Text, out perCorso) || 
     !decimal.TryParse(textBoxAgilitySmallVelocita.Text, out smallVelocita)) { 
     // invalid input data, e.g. "bla-bla-bla" 
     textBoxAgilitySmallTps.Text = "???"; 

     return; 
    } 

    try { 
     // ...then compute: put the right formula here 
     // put break point here, check smallVelocita and perCorso values 
     decimal result = smallVelocita/perCorso; 

     textBoxAgilitySmallTps.Text = result.ToString(); 
    } 
    catch (ArithmeticException) { 
     // Division by zero, overflow 
     textBoxAgilitySmallTps.Text = "???"; 
    } 
    } 

    ... 

    void TextBoxPercorsoTextChanged(object sender, EventArgs e) { 
    // Just a simple call, no complex logic here 
    ComputeSmallTps(); 
    } 

    void TextBoxAgilitySmallVelocitaTextChanged(object sender, EventArgs e) { 
    ComputeSmallTps(); 
    }