Need help with accepting decimals as input in C#

我与影子孤独终老i 提交于 2019-12-04 04:46:45

问题


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 have.

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

    namespace Project_2
{
class Program
{
    static void Main(string[] args)
    {
        int sideA = 0;
        int sideB = 0;
        double sideC = 0;
        Console.Write("Enter a integer for Side A ");
        sideA = Convert.ToInt16(Console.ReadLine());
        Console.Write("Enter a integer for Side B ");
        sideB = Convert.ToInt16(Console.ReadLine());
        sideC = Math.Pow((sideA * sideA + sideB * sideB), .5);
        Console.Write("Side C has this length...");
        Console.WriteLine(sideC);
        Console.ReadLine();

    }
}
} 

I have been trying to research this by using the Math.Abs and so on only to receive build errors. Help in the write path would be greatly appreciated.


回答1:


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




回答2:


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();
        }



回答3:


static decimal RequestDecimal(string message)
{
    decimal result;
    do 
    {
         Console.WriteLine(message);
    }
    while (!decimal.TryParse(Console.ReadLine(), out result));
    return result;
}


来源:https://stackoverflow.com/questions/7286455/need-help-with-accepting-decimals-as-input-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!