对C#来说相当新鲜。我有以下代码来计算两点之间的距离和角度。但是,它不会显示小数点(需要小数点后三位。我认为浮点数据类型可以处理十进制数?
e.g。点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);
}
}
}
答案 0 :(得分:2)
float deltaY = point2Y - point2X;
您在上面的行中有一个错误。你需要计算:
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);