2016-04-03 47 views
1

對於C#來說相當新穎。我有以下代碼來計算兩點之間的距離和角度。然而,它不會顯示小數點(需要小數點後三位,我認爲浮點數據類型可以處理十進制數字嗎?C#中的小數點#

例如,點1 x = 2,點1 y = 2,點2 x = 1,點2 y = 1。

距離計算爲1,角度計算爲-1距離應該是1.414 &角度應該是-135.000度,所以它就像它將它們向上/向下四捨五入感...

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

namespace AngleDistanceCalc 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // print welcome message 
      Console.WriteLine("Welcome. This application will calculate the distance between two points and display the angle."); 

      Console.WriteLine("Please enter point 1 X value:"); 
      float point1X = float.Parse(Console.ReadLine()); 

      Console.WriteLine("Please enter point 1 Y value:"); 
      float point1Y = float.Parse(Console.ReadLine()); 

      Console.WriteLine("Please enter point 2 X value:"); 
      float point2X = float.Parse(Console.ReadLine()); 

      Console.WriteLine("Please enter point 2 y value:"); 
      float point2Y = float.Parse(Console.ReadLine()); 

      float deltaX = point2X - point1X; 
      float deltaY = point2Y - point2X; 

      double distance = Math.Sqrt(deltaX * deltaX + deltaY * deltaY); 

      Console.WriteLine("The distance between the points is: {0}", distance); 

      Console.WriteLine("The angle between the points is: {0}", deltaX); 
     } 
    } 
} 
+1

'它不會顯示小數點' – Eser

+0

點1 x = 2,點1 y = 2,點2 x = 1,點2 y = 1。距離計算爲1,角度計算爲-1。距離應該是1.414,角度應該是-135.000度,所以如果這是合理的,它就像是將它們四捨五入... – SamFarr

+0

不,它沒有意義。我的數學足以做到這一點,我的問題是:'你得到的輸出是什麼,你期望的是什麼?'顯示具體的樣本... – Eser

回答

2
float deltaY = point2Y - point2X; 

你必須在ab中的錯誤ove線。你需要計算:

float deltaY = point2Y - point1Y; 

此外,你需要引入計算角度的邏輯。該公式在this answer下討論:

var angle = Math.Atan2(deltaY, deltaX) * 180/Math.PI; 
Console.WriteLine("The angle between the points is: {0}", angle); 
+0

啊,這是有道理的。解決了!謝謝!我怎樣才能將輸出顯示爲小數點後三位? – SamFarr

+0

@SamFarr:使用[Numeric(「N」)格式說明符](https://msdn.microsoft.com/en-us/library/dwhawy9k(v = vs.110).aspx#Anchor_6):'Console。 WriteLine(「點之間的角度是:{0:N3}」,角度);' – Douglas

+0

@LutzL:你是對的;感謝您指出了這一點。我已經糾正了答案。 – Douglas