Skip to content

Instantly share code, notes, and snippets.

@gwo0d
Last active October 7, 2021 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwo0d/fc33db22433be58c8a0b42afa6068ade to your computer and use it in GitHub Desktop.
Save gwo0d/fc33db22433be58c8a0b42afa6068ade to your computer and use it in GitHub Desktop.
Celsius-Fahrenheit-Convertor
using System;
namespace Celsius_Fahrenheit_Convertor
{
public class Convertor
{
private double _celsius = 0;
private double _fahrenheit = 0;
private int _choice;
/*
* Choice 1 = Celsius to Fahrenheit
* Choice 2 = Fahrenheit to Celsius
*/
public Convertor(int choice, double value)
{
_choice = choice;
switch (choice)
{
case 1:
_celsius = value;
_fahrenheit = (_celsius * 1.8) + 32;
break;
case 2:
_fahrenheit = value;
_celsius = (_fahrenheit - 32) / 1.8;
break;
}
}
public double Answer()
{
switch (_choice)
{
case 1:
return Math.Round(_fahrenheit, 2);
break;
case 2:
return Math.Round(_celsius, 2);
break;
default:
return 0;
}
}
}
}
using System;
namespace Celsius_Fahrenheit_Convertor
{
class Program
{
static void Main(string[] args)
{
bool go = true;
while (go)
{
try
{
Console.Write(
"- Enter 1 to convert Celsius to Fahrenheit\n- Enter 2 to convert Fahrenheit to Celsius\n- Enter 3 to exit\n: ");
int choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.Write("\nEnter a value in Celsius\n: ");
double celsius = double.Parse(Console.ReadLine());
Convertor convertorObjectCelsius = new Convertor(choice, celsius);
Console.WriteLine($"\n{celsius}°C = {convertorObjectCelsius.Answer()}°F\n");
break;
case 2:
Console.Write("\nEnter a value in Fahrenheit\n: ");
double fahrenheit = double.Parse(Console.ReadLine());
Convertor convertorObjectFahrenheit = new Convertor(choice, fahrenheit);
Console.WriteLine($"\n{fahrenheit}°F = {convertorObjectFahrenheit.Answer()}°C\n");
break;
case 3:
go = false;
break;
default:
Console.WriteLine("\nInvalid option entered! Please try again\n");
break;
}
}
catch (Exception e)
{
Console.WriteLine($"\nAn unexpected error has occurred: {e}\n");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment