Applied Programming/Conditions/C Sharp

conditions.csEdit

// This program asks the user for a Fahrenheit temperature, 
// converts the given temperature to Celsius,
// and displays the results.
//Input:
//     Fahrenheit temperature
// Output:
//     Fahrenheit temperature
//    Celsius temperature
// Example:
//    Enter Fahrenheit temperature:
//    100
//    100.0° Fahrenheit is 37.8° Celsius
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/C_Sharp_Programming
//     https://en.wikiversity.org/wiki/Applied_Programming/Functions/Python3
//     https://en.wikiversity.org/wiki/Programming_Fundamentals/Functions/C_Sharp
//     https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions
//     https://www.dofactory.com/reference/csharp-coding-standards

using System;

class MainClass
{
    const int TemperatureDifference = 32;
    const double TemperatureRatio = 5.0 / 9.0;
    const double AbsoluteZero = -459.67;

    public static void Main (string[] args)
    {
        var fahrenheit = GetFahrenheit();
        var celsius = ConvertFahrenheitToCelsius(fahrenheit);
        DisplayResult(fahrenheit, celsius);
    }

    private static double GetFahrenheit()
    {
        Console.WriteLine("Enter Fahrenheit temperature: ");
        var input = Console.ReadLine();        

        try
        {
            var fahrenheit = Convert.ToDouble(input);
            if (fahrenheit < AbsoluteZero)
            {
                Console.WriteLine("Fahrenheit temperature cannot be below absolute zero.");
                Console.WriteLine($"ArgumentOutOfRangeException: '{fahrenheit}' is invalid.");
                Environment.Exit(1);
            }

            return fahrenheit;
        }
        catch (System.FormatException)
        {
            Console.WriteLine("Fahrenheit temperature must be a floating point value.");
            Console.WriteLine($"FormatException: '{input}' is invalid.");
            Environment.Exit(2);
            return 0; //Never used
        }
    }

    private static double ConvertFahrenheitToCelsius(double fahrenheit)
    {
        System.Diagnostics.Debug.Assert(fahrenheit >= AbsoluteZero);
        
        var celsius = (fahrenheit - TemperatureDifference) * TemperatureRatio;

        return celsius;
    }

    private static void DisplayResult(double fahrenheit, double celsius)
    {
        Console.WriteLine(fahrenheit.ToString() + "° Fahrenheit is " + celsius + "° Celsius");
    }
}

Try ItEdit

Copy and paste the code above into one of the following free online development environments or use your own C# compiler / interpreter / IDE.

See AlsoEdit