Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Application Programming › My simple Fahrenheit to Celcius converter in C#
New Posts  All Forums:Forum Nav:

My simple Fahrenheit to Celcius converter in C#

post #1 of 15
Thread Starter 
I thought I'd make it easy for people to look at how C# code works. It's overly commented, for people who is not familiar to programming or C# to know what is actually going on:

Code:
using System;
using System.Collections.Generic;
using System.Text;

//
// Name: Sebastian 'gonX' Jensen
// Date: 4. Nov 09
// Program: A simple Fahrenheit from/to Celcius converter
// Known to compile fine in: Microsoft Visual Express C# 2008
// Comments:    In this program I've used simple commands which should be fairly straightforward to understand.
//              Please notice that I've moved Main() to the bottom of the document so that it does not complain
//              that it's missing some functions that I'm calling from Main(). Yes, I could have assigned them
//              earlier in the program, but this is less confusing to look at.
//              Please throw me a PM on Overclock.net if you do not understand parts of my code - my username is gonX.
//

namespace switcheslawl
{
    class Program
    {
        // Here's an example of how Main() is not the first variable in the program.
        static void toFahrenheit()
        {
            // Let's assign the variables we need. We use double so that we don't get unnecessary rounding.
            string temporary;
            double input;
            double temperature;

            // Clear it so that it doesn't look messy.
            Console.Clear();

            // Here I'll be telling the user to input his temperature in degrees celcius.
            // Please notice that I am not using Console.WriteLine(), but instead Console.Write()
            // I'm using a temporary variable as calculating with a string is troublesome,
            // it is parsed to a double throughout the code though.
            // This is what makes C# different from C++ - in C++ I would not have needed to parse it.
            Console.Write("Please enter the temperature in °C: ");
            temporary = Console.ReadLine();
            input = double.Parse(temporary);
            temperature = input * 1.8 + 32;

            // The :N2 tells the program to only output 2 decimals. They're rounded off, which is not that
            // good for people who actively work with numbers, but it'll work for most people.
            Console.Write("\
{0 :N2} °C is {1 :N2} °F\
Press a button to continue\
", input, temperature);
            Console.ReadKey();
        }

        static void toCelcius()
        {
            // All this is the same as in the toFahrenheit() static, except that the formula for calculating is different.
            string temporary;
            double input;
            double temperature;
            Console.Clear();
            Console.Write("Please enter the temperature in °F: ");
            temporary = Console.ReadLine();
            input = double.Parse(temporary);
            temperature = (input - 32) / 1.8;
            Console.Write("\
{0 :N2} °F is {1 :N2} °C\
Press a button to continue\
", input, temperature);
            Console.ReadKey();
        }
        static void Main()
        {
            // Here I have to assign option to 0, otherwise it'd complain about option not being assigned
            string option = "0";

            // I can type "stop" to stop the program.
            while (option != "stop")
            {
                Console.Clear();
                Console.WriteLine("What do you want to calculate to?\
\
F. To Fahrenheit\
C. To Celcius\
stop to stop.");
                option = Console.ReadLine();

                // Most people should be acquainted with switches if they've been programming before. This is fairly similar to C++ syntax.
                switch (option.ToLower())
                {
                    case "f":
                        toFahrenheit();
                        break;
                    case "c":
                        toCelcius();
                        break;
                    default:
                        option = "stop";
                        break;
                }
            }
        }
    }
}
Suggestions to clean up my code wouldn't be bad either
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
post #2 of 15
Nice work. Code seems clean to me, but I do have a couple of other suggestions if you don't mind.

I don't know about anyone else, but I always initialize my variables and assign them a value (null, blank, 0, etc).

Such as:
Code:
string temporary = "";
double input = 0;
double temperature = 0;

//You can also keep multiple variables of the same type on one line
string temporary = "";
double input = 0, temperature = 0;
Plus, the code below requires temperature to be assigned, similar to your string option requirement in Main().

I'm not sure how simple you want to keep this, but you could replace Parse with TryParse for an easy error checking example.
Code:
// TryParse takes a string and outputs to a double, while returning a boolean value
// Create a bool variable to test whether the conversion was successful
bool convert = double.TryParse(temporary, out input);

// If the conversion was successful and the bool is true, complete the method
if (convert)
{
    temperature = input * 1.8 + 32;
    Console.Write("\
{0 :N2} °C is {1 :N2} °F\
Press a button to continue\
", input, temperature);
    Console.ReadKey();
}
// If the conversion failed and the bool is false, display an error message
else
{
    Console.WriteLine("You must enter a valid number. Press key to start over.");
    Console.ReadKey();
    // Run the same method
    toFarenheit();
}

Again, nice work. Little examples like this would have come in handy when I was first learning C#.
Nevermore
(16 items)
 
  
CPUMotherboardGraphicsRAM
i5-2500k GIGABYTE GA-Z68A-D3H-B3 EVGA GTX 560 Ti G.SKILL Ripjaws 2 x 2GB 
Hard DriveOptical DriveCoolingOS
Western Digital Caviar Blue Sony DVD Burner Cooler Master Hyper 212+ Windows 7 Pro x64 
MonitorMonitorKeyboardPower
Acer 22" Widescreen X2Gen 19" Logitech Wave Corsair TX650W 
CaseMouseMouse PadAudio
Antec Three Hundred Microsoft Sidewinder Winner 3 Logitech X-540 5.1 
  hide details  
Reply
Nevermore
(16 items)
 
  
CPUMotherboardGraphicsRAM
i5-2500k GIGABYTE GA-Z68A-D3H-B3 EVGA GTX 560 Ti G.SKILL Ripjaws 2 x 2GB 
Hard DriveOptical DriveCoolingOS
Western Digital Caviar Blue Sony DVD Burner Cooler Master Hyper 212+ Windows 7 Pro x64 
MonitorMonitorKeyboardPower
Acer 22" Widescreen X2Gen 19" Logitech Wave Corsair TX650W 
CaseMouseMouse PadAudio
Antec Three Hundred Microsoft Sidewinder Winner 3 Logitech X-540 5.1 
  hide details  
Reply
post #3 of 15
The toXXX() methods do too much. Gathering input from the user and outputting the results to the console doesn't belong in "temperature conversion" methods. I suggest that you refactor the methods out into a new "temperature conversion" class.
post #4 of 15
Thread Starter 
Quote:
Originally Posted by Spotswood View Post
The toXXX() methods do too much. Gathering input from the user and outputting the results to the console doesn't belong in "temperature conversion" methods. I suggest that you refactor the methods out into a new "temperature conversion" class.
Do you suggest that I merged it all to Main()?
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
post #5 of 15
Quote:
Originally Posted by gonX View Post
Do you suggest that I merged it all to Main()?
No. This is what I mean:

Code:
class TemperatureConverter
{
    public double ToFahrenheit() { ... }
    public double ToCelcius() { ... }
}

void Main()
{
    TemperatureConverter converter = new TemperatureConverter();

    // read temp and scale from user...

    double result = converter.ToXXX();

    // display temp to user...
}
Designed this way the TemperatureConverter class only does conversions.
post #6 of 15
Thanks for this, I'm currently taking a C# class right now, so this will be quite a bit of help. We learned about setting up multiple methods last night, but the parameters threw me off a bit, heh.
Thing 3
(13 items)
 
  
CPUMotherboardGraphicsRAM
AMD Phemon II X4 955 ASUS M4A785TD-V EVO ASUS 6870 1GB 256-bit GDDR5 G.Skill "Ripjaw" 6GB PC3 12800 
Hard DriveOptical DriveOSMonitor
WD 500GB + WD 80GB DVD-RW Windows 7 Ultimate x64 x2 ASUS VH242 24" Monitors 
KeyboardPowerCaseMouse
Microsoft Ergonomic 4000 700W DangerDen Torture Rack Logitech MX 518 
Mouse Pad
Black with wrist pad 
  hide details  
Reply
Thing 3
(13 items)
 
  
CPUMotherboardGraphicsRAM
AMD Phemon II X4 955 ASUS M4A785TD-V EVO ASUS 6870 1GB 256-bit GDDR5 G.Skill "Ripjaw" 6GB PC3 12800 
Hard DriveOptical DriveOSMonitor
WD 500GB + WD 80GB DVD-RW Windows 7 Ultimate x64 x2 ASUS VH242 24" Monitors 
KeyboardPowerCaseMouse
Microsoft Ergonomic 4000 700W DangerDen Torture Rack Logitech MX 518 
Mouse Pad
Black with wrist pad 
  hide details  
Reply
post #7 of 15
Thread Starter 
Can somebody tell me why "input" here always returns 0?

Code:
using System;
using System.Collections.Generic;
using System.Text;

//
// Name: Sebastian 'gonX' Jensen
// Date: 4. Nov 09
// Revised: 14. Jan 10
// Program: A simple Fahrenheit from/to Celcius converter
// Known to compile fine in: Microsoft Visual Express C# 2008
// Comments:    In this program I've used simple commands which should be fairly straightforward to understand.
//              Please notice that I've moved Main() to the bottom of the document so that it does not complain
//              that it's missing some functions that I'm calling from Main(). Yes, I could have assigned them
//              earlier in the program, but this is less confusing to look at.
//              Please throw me a PM on Overclock.net if you do not understand parts of my code - my username is gonX.
//

namespace fahrenheitCelciusConv
{
    class Program
    {
        static void Main()
        {

            string option = "0";
            string temporary = "100";
            double input = 0;
            double temperature = 0;

            Console.WriteLine("You will select what temperature to convert to in the next process.\
");

            while (option == "0")
            {
                Console.Write("Please enter the temperature you wish to convert: ");
                temporary = Console.ReadLine();
                bool errorcheck = double.TryParse(temporary, out temperature);
                if (errorcheck == false)
                {
                    Console.Clear();
                    Console.WriteLine("You must enter a valid number. Please try again.\
");
                }
                else
                {
                    option = "1";
                    Console.Clear();
                }
            }
            while (option != "stop")
            {
                Console.WriteLine("\
What do you want to calculate to?\
Current temperature value is {0}\
\
F    To Fahrenheit\
C    To Celcius\
S    to set a new temperature\
E    to exit.", input);
                option = Console.ReadLine();
                switch (option.ToLower())
                {
                    case "f":  
                        temperature = (input * 1.8) + 32;
                        Console.Write("\
{0 :N2} °C is {1 :N2} °F\
Press a button to continue\
", input, temperature);
                        Console.ReadKey();
                        Console.Clear();
                        break;
                    case "c":
                        temperature = (input - 32) / 1.8;
                        Console.Write("\
{0 :N2} °F is {1 :N2} °C\
Press a button to continue\
", input, temperature);
                        Console.ReadKey();
                        Console.Clear();
                        break;
                    case "s":
                        Console.Write("\
Please enter the temperature: ");
                        temporary = Console.ReadLine();
                        bool errorcheck = double.TryParse(temporary, out temperature);
                        if (errorcheck)
                        {
                            Console.Clear();
                            break;
                        }
                        else
                        {
                            Console.WriteLine("You must enter a valid number. Please try again.\
");
                            temporary = "0";
                            break;
                        }
                    default:
                        option = "stop";
                        break;
                }
            }
        }
    }
}

Edited by gonX - 1/13/10 at 4:56pm
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
post #8 of 15
I see where you have declared input
Code:
double input = 0;
and the next time I see input is here.
Code:
Console.WriteLine("\
What do you want to calculate to?\
Current temperature value is {0}\
\
F    To Fahrenheit\
C    To Celcius\
S    to set a new temperature\
E    to exit.", input);
I don't see where you actually set a value to input, so input is always 0.



In the first TryParse you are using temperature, but should you be using input? Which if that's the case, it should also be changed in the TryParse in your switch statement.
Code:
bool errorcheck = double.TryParse(temporary, out temperature);
Nevermore
(16 items)
 
  
CPUMotherboardGraphicsRAM
i5-2500k GIGABYTE GA-Z68A-D3H-B3 EVGA GTX 560 Ti G.SKILL Ripjaws 2 x 2GB 
Hard DriveOptical DriveCoolingOS
Western Digital Caviar Blue Sony DVD Burner Cooler Master Hyper 212+ Windows 7 Pro x64 
MonitorMonitorKeyboardPower
Acer 22" Widescreen X2Gen 19" Logitech Wave Corsair TX650W 
CaseMouseMouse PadAudio
Antec Three Hundred Microsoft Sidewinder Winner 3 Logitech X-540 5.1 
  hide details  
Reply
Nevermore
(16 items)
 
  
CPUMotherboardGraphicsRAM
i5-2500k GIGABYTE GA-Z68A-D3H-B3 EVGA GTX 560 Ti G.SKILL Ripjaws 2 x 2GB 
Hard DriveOptical DriveCoolingOS
Western Digital Caviar Blue Sony DVD Burner Cooler Master Hyper 212+ Windows 7 Pro x64 
MonitorMonitorKeyboardPower
Acer 22" Widescreen X2Gen 19" Logitech Wave Corsair TX650W 
CaseMouseMouse PadAudio
Antec Three Hundred Microsoft Sidewinder Winner 3 Logitech X-540 5.1 
  hide details  
Reply
post #9 of 15
Thread Starter 
The TryParse statement was the conflict indeed, it was supposed to be 'out input', not 'out temperature' - thanks
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
post #10 of 15
Thread Starter 
Updated, working code:

Code:
using System;
using System.Collections.Generic;
using System.Text;

//
// Name: Sebastian 'gonX' Jensen
// Date: 4. Nov 09
// Revised: 14. Jan 10
// Program: A simple Fahrenheit from/to Celcius converter
// Known to compile fine in: Microsoft Visual Express C# 2008
// Comments:    In this program I've used simple commands which should be fairly straightforward to understand.
//              Please throw me a PM on Overclock.net if you do not understand parts of my code - my username is gonX.
//

namespace fahrenheitCelciusConv
{
    class Program
    {
        static void Main()
        {

            string option = "0";
            string temporary;
            double input = 0;
            double temperature;

            Console.WriteLine("You will select what temperature to convert to in the next process.\
");

            while (option == "0")
            {
                Console.Write("Please enter the temperature you wish to convert: ");
                temporary = Console.ReadLine();
                bool errorcheck = double.TryParse(temporary, out input);
                if (errorcheck == false)
                {
                    Console.Clear();
                    Console.WriteLine("You must enter a valid number. Please try again.\
");
                }
                else
                {
                    option = "1";
                    Console.Clear();
                }
            }
            while (option != "stop")
            {
                Console.WriteLine("\
What do you want to calculate to?\
Current temperature value is {0}\
\
F    To Fahrenheit\
C    To Celcius\
S    to set a new temperature\
E    to exit.", input);
                option = Console.ReadLine();
                switch (option.ToLower())
                {
                    case "f":  
                        temperature = (input * 1.8) + 32;
                        Console.Write("\
{0 :N2} °C is {1 :N2} °F\
Press a button to continue\
", input, temperature);
                        Console.ReadKey();
                        Console.Clear();
                        break;
                    case "c":
                        temperature = (input - 32) / 1.8;
                        Console.Write("\
{0 :N2} °F is {1 :N2} °C\
Press a button to continue\
", input, temperature);
                        Console.ReadKey();
                        Console.Clear();
                        break;
                    case "s":
                        Console.Write("\
Please enter the temperature: ");
                        temporary = Console.ReadLine();
                        bool errorcheck = double.TryParse(temporary, out input);
                        if (errorcheck)
                        {
                            Console.Clear();
                            break;
                        }
                        else
                        {
                            Console.WriteLine("You must enter a valid number. Please try again.\
");
                            temporary = "0";
                            break;
                        }
                    default:
                        option = "stop";
                        break;
                }
            }
        }
    }
}
It can still be made less complex - but I have a test in a couple of hours and I need to sleep on this first.
Edited by gonX - 1/13/10 at 5:44pm
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
I Have Sand
(13 items)
 
  
CPUMotherboardGraphicsRAM
i7 2600K@48x100.0 1.46v #L040B16 ASUS P8P67 Pro XFX Radeon 6950->6970 Corsair CMX8GX3M2A2000C9 
Hard DriveOptical DriveOSMonitor
120GB Agility3 + 2TB Hitachi Samsung Combo SATA Windows 7 Ultimate Dell U2711 (right) + Samsung 226CW (left) 
KeyboardPowerCaseMouse
Ducky DK9008-B OCN edition. MX Browns Corsair TX850 Antec Three Hundred SteelSeries Xai 
Mouse Pad
QPAD HeatoN XL (M when LANing) 
  hide details  
Reply
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Application Programming
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Application Programming › My simple Fahrenheit to Celcius converter in C#