2011-01-27 5 views
2

저는 C#을 배우는 데 도움이되는 온도 변환기를 만들기 위해 노력하고 있습니다. 나는 단지 기초의 대부분을 알고 있고, 이것은 내가 지금까지 생각 해낸 것이다. 내가 붙어있는 것은 사용자가 넣은 숫자를 가져다가 사용자가 이전에 입력 한 선택 항목으로 바꾸거나 아니면 섭씨로 바꾸는 것입니다. 다시 말하지만, 나는 기초 만 알고 있지만 도움은 매우 감사 할 것입니다. 이하지만, 귀하의 질문에 대답하면 당신은 당신이 화씨 20 ° C를 변환 할 의미 "섭씨 20"같은 것을 입력 가정자체 교육 : 초보자가 온도 변환기를 만들려고합니다

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; 
      } 
     } 
    } 
} 

답변

0

, 당신은 확실하지 않음이

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 

같은 몇 가지 논리가 필요합니다.

더 나은 방법은 켈빈을 지원하는 것입니다. 사용자가 입력 한대로 입력 온도를 켈빈으로 변환 한 다음 켈빈을 사용자가 원하는대로 변환하십시오. 당신은 5 개 또는 10 다른 단위에 대한이 코드 대신에 얼마나 상상

any unit -> kelvin -> any other unit 

을 당신은 장점이 표시되지 않는 경우 : 그럼 당신은 개별적으로 각각의 경우를 처리 할 필요없이 단위의 어떤 종류에서 /로 변환 지원 단지 2.

0

당신은 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는 프로그래밍 학습 중이므로 가장 간단한 예제를 사용했습니다).

편집 내 알고리즘을 수정했습니다. 이제 논리는 실제로 의도 한대로 작동합니다.

0

어때? 객체 접근 방식을 사용

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; 
     } 
    } 

}

0

는 ....

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 
    } 
} 

그런 다음 메인 클래스는 것 ... # 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; 
      } 
     } 
    } 
0

프로그램에는 몇 가지 단점이 있습니다. 먼저 사용자가 수행하고자하는 변환 유형을 저장해야하기 때문에 변환해야하는 온도가 입력되었을 때 실제로 수행 할 수 있습니다. 화씨와 섭씨 (어쨌든 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; 
      } 
     } 
    } 
} 

참고 :

그래서, 여기 당신이 내 제안을 반영하기 위해 프로그램을 변경할 수있는 방법이다,라고 한 유효한 값이 얻어진다.

본인이 추가 학습을 위해 올바른 방향으로 안내하기를 바랍니다. 위와 관련하여 질문이 있으시면 언제든지 물어보십시오. 면책 조항으로서 위의 코드를 컴파일하지 않았지만 내 정신 구문 검사기는 대개 신뢰할 만합니다 .-)