[英]Celsius to Fahrenheit Conversion Form
我正在嘗試創建一種將攝氏溫度轉換為華氏溫度,反之亦然的窗體,但是轉換按鈕代碼出現錯誤。 我得到的問題是,變量ConvertedTemperature保留為空,因此如果驗證失敗,則消息將通過輸出標簽(lblConvertedTemperature)顯示。 但是由於將此留空,我得到了未分配變量錯誤的使用。 我的問題是如何重新措辭處理部分,以免導致此錯誤。
Double inputTemperature;// the variable that will store txtTemperatureInput for calculation
Double convertedTemperature;// the variable that will store the converted temperature
/*********************************
* INPUT *
* *******************************/
// when the user inputs a value and clicks calculate, the input must first be validated
if (Double.TryParse(txtTemperatureInput.Text, out inputTemperature) == false)
{
lblConvertedTemperature.Text = "Temperature must be a numeric value.";// message displayed in
//output label telling user their input was not accepted because it was not numeric
txtTemperatureInput.Focus();// sets the focus back onto the temperature textbox for a new entry
}
else
{
/*******************************
* PROCESSING *
*******************************/
if (optConvertToCelsius.Checked == true)// if the convert to celsius radio button is selected
// this statement will run
{
convertedTemperature = (inputTemperature - 32)*5 / 9;// the formula for converting
//Fahrenheit to Celsius
}
else if (optConvertToFahrenheit.Checked == true)// convert to fahrenheit was selected,
//meaning the convert to fahrenheit radio button was selected, so this statement will run
{
convertedTemperature = (inputTemperature * 9) / 5 + 32; ;// the formula for converting Celsius to
//Fahrenheit
}//end concatonated if
}//end if
/******************************
*OUTPUT *
******************************/
lblConvertedTemperature.Text = Math.Round(convertedTemperature, 4).ToString();// sets the converted temperature
// label to the value of convertedTemperature
}
}
}
我的問題是如何重新措辭處理部分,以免導致此錯誤。
好了,編譯器關心兩種情況:
lblConvertedTemperature.Text
無論如何都已經在更改lblConvertedTemperature.Text
...因此只需返回即可。 (然后,您不需要else
子句,這意味着您將減少嵌套-始終易於閱讀。) optConvertToCelsius
也optConvertToFahrenheit
選中optConvertToFahrenheit
。 編譯器會考慮這種情況,因為您要檢查兩個單獨的條件。 當然,您可能知道它永遠不會發生。 對於后者,我建議只刪除第二個條件:
if (optConvertToCelsius.Checked)
{
...
}
else
{
...
}
請注意,就樣式而言,我從第一個條件中刪除了== true
。
現在,編譯器將知道,如果到此為止,將執行這兩個塊之一 。 當兩個塊都分配給convertedTemperature
,肯定會在該代碼的末尾分配該變量。
編輯:只是澄清一下,如果您有:
if (someCondition)
{
...
}
else if (someOtherCondition)
{
...
}
不管條件如何,編譯器都不會假定將執行這些塊之一。 即使您知道完全符合一個條件,編譯器也只會遵循其相對簡單的規則。
您正在確定范圍。 只需移動
/******************************
*OUTPUT *
******************************/
lblConvertedTemperature.Text = Math.Round(convertedTemperature, 4).ToString();// sets the converted temperature
// label to the value of convertedTemperature
到“加工”范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.