...

View Full Version : Simple C# Question



DarkLightA
11-24-2010, 03:28 PM
I've coded my first program in C#. It's for finding the square root of a number. This is my code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What number?");
string dPre = Console.ReadLine();
decimal dDec = Convert.ToDecimal(dPre);
double d = Convert.ToDouble(dDec);
double sqrtLol = Math.Sqrt(d);
Console.WriteLine(sqrtLol);
Console.ReadLine();
}
static void

}
}


However it seems quite trivial to convert from string to decimal, and decimal to double. Isn't there an easier way?

ess
12-01-2010, 10:34 AM
Hi DarkLight

You can convert from string to double this by using the parse method



string dPre = Console.ReadLine();
double d = double.Parse( dPre );


Please note that a FormatException might be thrown if the user enters non-numerical characters....so, I would use a try catch block to handle the user input

Cheers
~E

SresSi
12-04-2010, 01:25 PM
Or use Double.TryParse.

More at:
http://msdn.microsoft.com/en-us/library/3s27fasw.aspx



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum