Overclock.net - Overclocking.net
     
 
Home Gallery Reviews Blogs Register Today's Posts Mark Forums Read Members List


Go Back   Overclock.net - Overclocking.net > Software, Programming and Coding > Coding and Programming > Application Programming

Reply
 
LinkBack Thread Tools
Old 2 Weeks Ago   #1 (permalink)
ZOMG Native Linux Client!
 
gonX's Avatar
 
intel nvidia

Join Date: May 2006
Location: Tampere, Finland
Posts: 20,922
Blog Entries: 10

FAQs Submitted: 1
Hardware Reviews: 15
Trader Rating: 13
Default My simple Fahrenheit to Celcius converter in C#

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("\n{0 :N2} °C is {1 :N2} °F\nPress a button to continue\n", 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("\n{0 :N2} °F is {1 :N2} °C\nPress a button to continue\n", 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?\n\nF. To Fahrenheit\nC. To Celcius\nstop 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
__________________
THE Mouse FAQ | 32-bit Resolution Fix | Important Information
64-Bit Driver Signing Fix | The Infraction and Warning System
My Anime Progress | The HoN Discussion Thread


Please direct all tech related questions to a thread in the respectable forums, and not to my PM inbox. Thank you

System: Certainly not the OS you'd expect
CPU
Intel Q6600 B3 @ 3 GHz
Motherboard
Gigabyte EP45-UD3P, F9b Bios
Memory
2x2048MB CorsairXMS DDR2-800 @ 500MHz 5-5-4-17
Graphics Card
Gigabyte 8800GT 512MB @ 686/1743/927
Hard Drive
3x250GB+2x200GB 4xMaxtor 1xHitachi
Sound Card
E-MU Tracker|pre USB
Power Supply
Cooler Master RS-550-ACLY 550W
Case
Antec Three Hundred
CPU cooling
Lapped Big Typhoon (stock fan) + AS5
GPU cooling
Stock
OS
Arch Linux i686
Monitor
IBM P275
gonX is offline Overclocked Account gonX's Gallery   Reply With Quote
Old 2 Weeks Ago   #2 (permalink)
Intel Overclocker
 
KC_Flip's Avatar
 
intel nvidia

Join Date: Aug 2008
Location: Missouri, USA
Posts: 393

Rep: 72 KC_Flip is acknowledged by some
Unique Rep: 71
Hardware Reviews: 1
Trader Rating: 0
Default

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("\n{0 :N2} °C is {1 :N2} °F\nPress a button to continue\n", 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#.
__________________
Quote:
Originally Posted by FlaKing View Post
TL;DR, Greasy guy at coffee shop was totally unreasonable, exacted my revenge by signing him up for horse porn.
3DMark06: 15689 ----------------------- E8400 C0 @ 4.0 Validation/Thread

System: Nevermore
CPU
E8400(C0) @ 4.0 (1.34 V-drop)
Motherboard
Asus 750i P5N-D
Memory
G.Skill 2x2GB 800 @ 883
Graphics Card
EVGA 9800GTX+ 800/2000/1200 I:42C/L:75C(Furmark)
Hard Drive
WD 320/Vista, 320/Games, 320/Storage
Sound Card
Onboard
Power Supply
Corsair TX650W
Case
Modded Antec Three Hundred
CPU cooling
Xigmatek HDT-S1283 w/ IC Diamond
GPU cooling
Stock
OS
Windows 7 Pro x64
Monitor
Acer 22" Widescreen + X2Gen 19"
KC_Flip is offline   Reply With Quote
Old 2 Weeks Ago   #3 (permalink)
Case Modder
 
Spotswood's Avatar
 
Join Date: Jul 2008
Location: New Hampshire, USA
Posts: 236

Rep: 46 Spotswood is acknowledged by some
Unique Rep: 39
Trader Rating: 0
Default

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.
__________________
Rich
Custom Wooden Case Builder
Overclock.net Mod of the Month
Spotswood is offline   Reply With Quote
Old 2 Weeks Ago   #4 (permalink)
ZOMG Native Linux Client!
 
gonX's Avatar
 
intel nvidia

Join Date: May 2006
Location: Tampere, Finland
Posts: 20,922
Blog Entries: 10

FAQs Submitted: 1
Hardware Reviews: 15
Trader Rating: 13
Default

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()?
__________________
THE Mouse FAQ | 32-bit Resolution Fix | Important Information
64-Bit Driver Signing Fix | The Infraction and Warning System
My Anime Progress | The HoN Discussion Thread


Please direct all tech related questions to a thread in the respectable forums, and not to my PM inbox. Thank you

System: Certainly not the OS you'd expect
CPU
Intel Q6600 B3 @ 3 GHz
Motherboard
Gigabyte EP45-UD3P, F9b Bios
Memory
2x2048MB CorsairXMS DDR2-800 @ 500MHz 5-5-4-17
Graphics Card
Gigabyte 8800GT 512MB @ 686/1743/927
Hard Drive
3x250GB+2x200GB 4xMaxtor 1xHitachi
Sound Card
E-MU Tracker|pre USB
Power Supply
Cooler Master RS-550-ACLY 550W
Case
Antec Three Hundred
CPU cooling
Lapped Big Typhoon (stock fan) + AS5
GPU cooling
Stock
OS
Arch Linux i686
Monitor
IBM P275
gonX is offline Overclocked Account gonX's Gallery   Reply With Quote
Old 2 Weeks Ago   #5 (permalink)
Case Modder
 
Spotswood's Avatar
 
Join Date: Jul 2008
Location: New Hampshire, USA
Posts: 236

Rep: 46 Spotswood is acknowledged by some
Unique Rep: 39
Trader Rating: 0
Default

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.
__________________
Rich
Custom Wooden Case Builder
Overclock.net Mod of the Month
Spotswood is offline   Reply With Quote
Old 1 Week Ago   #6 (permalink)
Programmer
 
Regulus's Avatar
 
amd nvidia

Join Date: May 2005
Location: San Antonio, Texas
Posts: 754

Rep: 68 Regulus is acknowledged by some
Unique Rep: 60
Trader Rating: 0
Default

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.
__________________
_██_
(ಠ_ರೃ)
Quote:
Talking about The Old Republic reviews with my brother on Facebook
I saw this one review, that was like "ToR is stoopid!" And I was liek "Nu uh, my bro says it's the bestest!" and they said "Yea right!" and attacked me with their ninja bears, which were actually pirate sharks with super capes of death, and I was like "Yea right" and summoned a whole fleet of flying howler monkeys and we fought and it was all epic. Thats what I heard

System: Thing 3
CPU
AMD X2 6000+ 3.0GHz
Motherboard
ASUS M2N-SLI Deluxe
Memory
G.Skill PC6400 DDR2 4GB
Graphics Card
eVga 8800GT 512MB
Hard Drive
WD 500GB + WD 80GB
Sound Card
Realtek Onboard
Power Supply
700W
Case
DangerDen Torture Rack
CPU cooling
TRUE
GPU cooling
Stock
OS
Windows 7 Pro x64
Monitor
x2 Asus VH242 24" Monitors
Regulus is offline   Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools



All times are GMT -5. The time now is 12:03 PM.


Overclock.net is a Carbon Neutral Site Creative Commons License

Terms of Service / Forum Rules | Privacy Policy | DMCA Info | Advertising | Become an Official Vendor
Copyright © 2009 Shogun Interactive Development. Most rights reserved.
Page generated in 0.12759 seconds with 8 queries