2013-10-24 28 views
1
class conv 
{ 

    public double input; 
    public double value; 
    public double ctf() 
    { 
     value = (9.0/5.0) * input + 32; 
     return value; 
    } 
    public double ftc() 
    { 
     value = (5.0/9.0) * (input - 32); 
     return value; 
    } 
} 

//需要兩個類。例如,當我輸入100並嘗試將攝氏溫度轉換成華氏度時,答案是32,而當從華氏溫度到攝氏時,答案是-17.7777777!我得到了他的代碼轉換攝氏度和華氏度沒有錯誤,但答案是錯的

public partial class Form1 : Form 
{ 
    double input = double.Parse(textBox1.Text); 
    try 
    { 

     conv cf = new conv(); 


     if (comboBox1.Text == "celsius to fahrenheit") 
     { 
      cf.ctf(); 
      label3.Text = cf.value.ToString(); 
     } 
     else if (comboBox1.Text == "fahrenheit to celsius") 
     { 
      cf.ftc(); 
      label3.Text = cf.value.ToString(); 

} 

回答

8

您根本沒有設置input字段值!

conv cf = new conv(); 

// set cf.input value 
cf.input = input; 

更新:不過說實話,你的代碼有質量真的很差。我會去與靜態方法,而不是實例的:

public static class TemperatureConverter 
{ 
    public static double ToFahrenheit(double celsius) 
    { 
     return (9.0/5.0) * celsius + 32; 
    } 

    public static double ToCelsius(double fahrenheit) 
    { 
     return (5.0/9.0) * (fahrenheit - 32); 
    } 
} 

示例用法:

if (comboBox1.Text == "celsius to fahrenheit") 
{ 
    label3.Text = TemperatureConverter.ToFahrenheit(input); 
} 
else if (comboBox1.Text == "fahrenheit to celsius") 
{ 
    label3.Text = TemperatureConverter.ToCelsius(input); 
} 
+0

+1的靜態輔助類! – gdoron

+0

也應手動計算9.0/5.0和5.0/9.0並定義爲常量。 – alexmac

+0

@Alexander編譯器將爲您做到這一點,imo。 – MarcinJuraszek