2011-09-02 25 views
3

我写了一个程序在C#运行毕达哥拉斯定理。我希望能够让程序接受来自用户输入的小数点的帮助。这是我的。需要帮助,接受小数作为输入在C#

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

    } 
} 
} 

我一直在试图通过使用Math.Abs​​等仅用于接收构建错误来研究此问题。写道中的帮助将不胜感激。

+3

使用Decimal.Parse()。 –

+0

如果我使用那么Math.Pow功能停止工作,因为它无法转换双为十进制 – Thomas

回答

3

我会推荐使用Decimal.TryParse。这种模式非常安全,因为它捕捉异常并返回一个布尔值来确定解析操作的成功。

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

+1

挑剔:一般来说,各种'TryParse'模式不会“陷阱”异常;他们完全避开它们。 – LukeH

+0

不够公平,但不会向用户公开任何异常。这就是为什么这是一个很好的模式。我也在自定义代码中使用这种模式。 – hivie7510

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

Math.Pow犯规采取十进制。关于Math.Pow和decimal,已经有另外一个问题了。使用双。

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

这就是诀窍。我的错误在于双方的任务。非常感谢您的帮助! – Thomas

+0

或尝试“为B面输入小数”;) – user3800527