我正在尝试制作一种常规形式,可以将摄氏温度转换为华氏温度,反之亦然。
private void button1_Click(object sender, EventArgs e)
{
double celsius;
double fahrenheit;
string value;
double finalValue;
bool successCelsius = double.TryParse(textBox1.Text, out celsius);
bool successFahrenheit = double.TryParse(textBox2.Text, out fahrenheit);
if (successCelsius == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
celsius = Convert.ToDouble(textBox1.Text);
finalValue = (celsius * 9) / 5 + 32;
label6.Text = finalValue.ToString();
label6.Text = celsius + " " + "degrees Celsius converts to" + " " + finalValue + " " + "degrees Fahrenheit";
}
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
fahrenheit = Convert.ToDouble(textBox2.Text);
finalValue = (fahrenheit - 32) * 5 / 9;
value = finalValue.ToString();
label6.Text = fahrenheit + " " + "degrees Fahrenheit converts to" + " " + finalValue + " " + "degrees Celsius";
}
}
文本框接受值并显示到label6。它检查输入的值是否为双精度值,然后它可以工作。 idk为什么tryParse无法正常工作。
可以帮帮我吗? :)
答案 0 :(得分:0)
此代码不起作用的原因是由于您的代码流。
现在代码的结构方式,您必须同时输入一个摄氏度和一个法氏值,否则您的代码将显示“ ERROR”。如果textbox1或textbox2为空,则您的代码将从TryParse返回false。如果遵循该逻辑,则将执行以下代码(如果仅输入摄氏度):
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
更新: 您需要分别处理这两种情况...这是一种简单的方法...检查并执行另一种方法。有很多方法可以“解决”此问题,但这将是最简单的方法之一。
private void button1_Click(object sender, EventArgs e)
{
double celsius;
double fahrenheit;
string value;
double finalValue;
if (textBox1.Text.Length > 0)
{
bool successCelsius = double.TryParse(textBox1.Text, out celsius);
if (successCelsius == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
celsius = Convert.ToDouble(textBox1.Text);
finalValue = (celsius * 9) / 5 + 32;
label6.Text = finalValue.ToString();
label6.Text = celsius + " " + "degrees Celsius converts to" + " " + finalValue + " " + "degrees Fahrenheit";
}
}
else
{
bool successFahrenheit = double.TryParse(textBox2.Text, out fahrenheit);
if (successFahrenheit == false)
{
label6.Text = ("ERROR: Please enter a numeric temperature to convert.");
return;
}
else
{
fahrenheit = Convert.ToDouble(textBox2.Text);
finalValue = (fahrenheit - 32) * 5 / 9;
value = finalValue.ToString();
label6.Text = fahrenheit + " " + "degrees Fahrenheit converts to" + " " + finalValue + " " + "degrees Celsius";
}
}
}