c# - 我得到了他的代码,转换摄氏度和华氏度没有错误,但是答案是错误的

标签 c#

 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/

相关文章:

c# - 如何在 Entity Framework 4 Designer 中分配默认值并定义唯一键

c# - 您最喜欢阅读 XML 文件的方式是什么?

c# - 绑定(bind)集合不起作用

c# - 当 ListView 的 ItemsSource 改变时触发事件

c# - 确定在抛出 OutOfMemoryException 之前可以使用的可用内存

c# - 属性最早出现在哪种语言中

c# - 具有 Oracle 数组绑定(bind)的 ExecuteReader

c# - 即使 autopostback=true,OnSelectedIndexChange 也不会触发

C# Form 在处理信息时卡住

c# - 使用 lambda 从对象及其列表创建通用列表