Need help with accepting decimals as input in C#

后端 未结 3 1195
鱼传尺愫
鱼传尺愫 2021-01-20 16:30

I have written a program in C# that runs the Pythagorean Theorem. I would love some help on allowing the program to accept decimal points from the user input. This is what I

相关标签:
3条回答
  • 2021-01-20 17:07

    I would recommend using Decimal.TryParse. This pattern is very safe since it traps the exceptions and returns a boolean to determine the success of the parse operation.

    http://msdn.microsoft.com/en-us/library/system.decimal.tryparse.aspx

    0 讨论(0)
  • 2021-01-20 17:14
    static decimal RequestDecimal(string message)
    {
        decimal result;
        do 
        {
             Console.WriteLine(message);
        }
        while (!decimal.TryParse(Console.ReadLine(), out result));
        return result;
    }
    
    0 讨论(0)
  • 2021-01-20 17:19

    Math.Pow doesnt take in decimal. There is already another question on SO about Math.Pow and decimal. Use double.

    static void Main(string[] args)
            {
                double sideA = 0;
                double sideB = 0; 
                double sideC = 0; 
                Console.Write("Enter an integer for Side A ");
                sideA = Convert.ToDouble(Console.ReadLine()); 
                Console.Write("Enter an integer for Side B ");
                sideB = Convert.ToDouble(Console.ReadLine()); 
                sideC = Math.Pow((sideA * sideA + sideB * sideB), .5); 
                Console.Write("Side C has this length..."); 
                Console.WriteLine(sideC); 
                Console.ReadLine();
            }
    
    0 讨论(0)
提交回复
热议问题