2016-04-03 8 views
1

です。私は2点間の距離と角度を計算する次のコードを持っています。しかし、小数点を表示することはありません(小数点以下3桁にする必要があります)。浮動小数点データ型で10進数を扱うことができると思いましたか?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

'それはあなたが何を期待するか、あなたが得る出力は何points'小数点以下を表示しないのだろうか? – 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のバグを持っていますオベライン。

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

ああ、意味があります。それを解決!ありがとうございました!出力を小数点以下3桁まで表示するにはどうすればよいですか? – SamFarr

+0

@SamFarr:[数値( "N")形式指定子](https://msdn.microsoft.com/en-us/library/dwhawy9k(v = vs.110).aspx#Anchor_6): 'コンソール。 WriteLine( "ポイント間の角度は{0:N3}"、angle); ' – Douglas

+0

@LutzL:そうです。それを指摘してくれてありがとう。私は答えを修正しました。 – Douglas

関連する問題