【问题标题】:Self-Teaching: Beginner trying to make a temperature converter自学:初学者尝试制作温度转换器
【发布时间】:2011-06-16 13:05:12
【问题描述】:

我正在尝试构建一个温度转换器来帮助自己学习 C#。我只知道大部分基础知识,这就是我到目前为止所想出的。我坚持的是,取用户输入的数字,并将其转换为用户先前输入的选择,即华氏温度或摄氏度。同样,我只知道基础知识,但非常感谢您的帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("What sort of temperature would you like to convert?");
            string tempType = Console.ReadLine();
            ConvertChoice(tempType.ToLower());
            Console.WriteLine("Please enter a temperature to convert: ");
            string temperatureString = Console.ReadLine();
            int temperature = int.Parse(temperatureString);
            Console.ReadLine();   
        }

        static void ConvertChoice(string tempType)
        {
            switch (tempType)
            {
                case "farenheit":
                    Console.WriteLine("Farenheit it is!");
                    return;
                case "celsius":
                    Console.WriteLine("Celsius it is!");
                    return;
                default:
                    Console.WriteLine("Invalid type, please type farenheit or celsius.");
                    return;
            }
        }
    }
}

【问题讨论】:

    标签: c# converter


    【解决方案1】:

    假设您输入诸如“Celsius, 20”之类的内容,这意味着您要将 20ºC 转换为华氏度,您需要一些这样的逻辑

    if type == fahrenheit
        result = [formula from fahrenheit to celsius, using 'temperature']
        restype = "celsius"
    else
        result = [formula from celsius to fahrenheit, using 'temperature']
        restype = "fahrenheit"
    
    print "The result is", result, "degrees", restype
    

    不过,不确定这是否能回答您的问题。

    还有一种更好的方式是支持 Kelvin。将输入温度从用户输入的任何内容转换为开尔文,然后将开尔文转换为用户想要的任何值。然后,您可以支持与任何类型的单位之间的转换,而无需单独处理每种情况:

    any unit -> kelvin -> any other unit
    

    如果您没有看到优势,想象一下您将如何为 5 或 10 个不同的单元进行编码,而不仅仅是 2 个。

    【讨论】:

      【解决方案2】:

      这个怎么样?

      namespace ConsoleApplication1
      {
          // Using an enum to store the result of 
          // parsing user input is good practice.
          public enum Scale
          {
            Unknown,
            Celsius,
            Farenheit
          }
      
      
          class Program
          {
      
              static void Main(string[] args)
              {
                  Console.WriteLine("What sort of temperature would you like to convert?");
                  string tempType = Console.ReadLine();
      
                  switch(ConvertChoice(tempType))
                  {
                    case Scale.Celsius:
                      // do celsius work here
                    break;
                    case Scale Farenheit:
                      // do farenheit work here
                    break;
                    default:
                      // invalid input work here  
                  }
                  Console.ReadLine();   
              }
      
              static Scale ConvertChoice(string tempType)
              {
                // use the framework.  also, when dealing with string equality, its best
                // to use an overload that uses the StringComparison enum.
                if(tempType.StartsWith("f", StringComparison.CurrentCultureIgnoreCase))
                  return Scale.Farenheit;
                if(tempType.StartsWith("c", StringComparison.CurrentCultureIgnoreCase)))
                  return Scale.Celsius;
                return Scale.Unknown;
              }
          }
      

      }

      【讨论】:

        【解决方案3】:

        使用对象方法....原谅一些可能的语法/样式错误,通常不要自己使用c#...

        class TempConverter 
        {
          public string degreeType {get; set;}
          public double userTemp {get; set;}
        
          public TempConverter(){}
        
          public double convert()
          { 
            switch(this.degreeType)
            {
               case "F":
                  return this.convertToF();
               case "C":
                  return this.convertToC();
               default:
                  return null;  
            }
        
          }
          public double convertToF()
          {
               return //user temp converted to F
          }
        
          public double convertToC()
          {
               return //user temp converted to C
          }
        }
        

        那么你的主类应该是这样的:

        class Program
            {
                static void Main(string[] args)
                {
                TempConverter converter = new TempConverter();
                    Console.WriteLine("What sort of temperature would you like to convert?");
                    converter.degreeType = Console.ReadLine();
                    ConvertChoice(converter.degreeType);
                    Console.WriteLine("Please enter a temperature to convert: ");
                    converter.userTemp = Convert.ToDouble(Console.ReadLine());
                    Console.WriteLine(Double.ToString(converter.convert());  
                }
        
                static void ConvertChoice(string tempType)
                {
                    switch (tempType)
                    {
                        case "farenheit":
                            Console.WriteLine("Farenheit it is!");
                            return;
                        case "celsius":
                            Console.WriteLine("Celsius it is!");
                            return;
                        default:
                            Console.WriteLine("Invalid type, please type farenheit or celsius.");
                            return;
                    }
                }
            }
        

        【讨论】:

          【解决方案4】:

          你的程序有一些缺点;首先你需要保存用户想要进行哪种类型的转换,这样你就可以在他/她输入需要转换的温度时实际执行它。由于您只使用两种温度类型(华氏温度和摄氏温度(是的,好吧,谁使用 Réaumur?))您可以将用户选择存储为布尔值,指示是否选择了华氏温度。您可能还想接受十进制数字。

          话虽如此,您可以通过以下方式更改程序以反映我的建议:

          namespace ConsoleApplication1
          {
              class Program
              {
                  static void Main(string[] args)
                  {
                      bool isFahrenheit;
                      bool temperatureTypeHasBeenDetermined = false;
                      while(!temperatureTypeHasBeenDetermined){
                          Console.WriteLine("What sort of temperature would you like to convert?");
                          string tempType = Console.ReadLine();
                          temperatureTypeHasBeenDetermined = ConvertChoice(tempType.ToLower(), out isFahrenheit);
                      }
                      decimal temperature;
                      bool temperatureEnteredCorrectly = false;
                      while(!temperatureEnteredCorrectly){
                          Console.WriteLine("Please enter a temperature to convert: ");
                          string temperatureString = Console.ReadLine();
                          temperatureEnteredCorrectly = decimal.TryParse(temperatureString, out temperature);
                      }
                      //Now we are ready to do the conversion
                      decimal convertedTemperature = isFahrenheit ?
                                                     ConvertFromFahrenheitToCelsius(temperature) :
                                                     ConvertFromCelsiusToFahrenheit(temperature);
                      string from = isFahrenheit ? "F" : "C";
                      string to = isFahrenheit ? "C" : "F";
          
                      Console.WriteLine("{0}{1} = {2}{3}", temperature, from, convertedTemperature, to);                
          
                      Console.ReadLine();   
                  }
          
                  static decimal ConvertFromFahrenheitToCelsius(decimal temperature)
                  {
                       //Implement properly
                       return 60m;
                  }
          
                  static decimal ConvertFromCelsiusToFahrenheit(decimal temperature)
                  {
                       //Implement properly
                       return 42m;
                  }
          
                  static bool ConvertChoice(string tempType, out bool isFahrenheit)
                  {
                      isFahrenheit = false;
                      switch (tempType)
                      {
                          case "fahrenheit":
                              Console.WriteLine("Fahrenheit it is!");
                              isFahrenheit = true;
                              return true;
                          case "celsius":
                              Console.WriteLine("Celsius it is!");
                              return false;
                          default:
                              Console.WriteLine("Invalid type, please type fahrenheit or celsius.");
                              return false;
                      }
                  }
              }
          }
          

          请注意,我已通过循环确保为温度类型和温度值输入正确的值,直到获得有效值。

          我希望这可以引导您朝着正确的方向进一步自学。如果您对上述内容有任何疑问,请不要犹豫。作为免责声明,我必须说我没有编译上面的代码,但我的心理语法检查器通常非常可靠;-)

          【讨论】:

            【解决方案5】:

            您已将他们的选择存储在 tempType 中。使用它。

            static double GetTemp(string tempChoice, int temperature)
            {
               double convertedTemp = 0.0;
            
               if(tempChoice.Equals("farenheit", StringComparison.CurrentCultureIgnoreCase))
               {
                   convertedTemp = ((double)temperature * 9.0/5.0) + 32.0;
               }
               else
               {
                   convertedTemp = ((double)temperature -32.0) * 5.0/9.0;
               }
            
               return convertedTemp;
            }
            

            只需从你的 main() 调用这个函数。

            (注意:是的,我意识到它的功能有限,并假设只有两种可能的温标。OP 说他正在学习编程,所以我选择了最简单的例子)。

            编辑 修复了我的算法。现在逻辑实际上按预期工作。

            【讨论】:

              猜你喜欢
              • 2011-12-14
              • 1970-01-01
              • 2012-10-15
              • 1970-01-01
              • 2015-09-15
              • 1970-01-01
              • 2014-06-21
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多