2011-09-02 41 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