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();
}
最佳答案
您根本没有设置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);
}
关于c# - 我得到了他的代码,转换摄氏度和华氏度没有错误,但是答案是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19556707/