C# C中的小数点#
对C#来说,这是个新鲜事。我有下面的代码来计算两点之间的距离和角度。但是,它不会显示小数点(需要精确到小数点后三位。我认为浮点数据类型可以处理十进制数C# C中的小数点#,c#,.net,visual-studio,math,floating-point,C#,.net,Visual Studio,Math,Floating Point,对C#来说,这是个新鲜事。我有下面的代码来计算两点之间的距离和角度。但是,它不会显示小数点(需要精确到小数点后三位。我认为浮点数据类型可以处理十进制数 e、 g.点1X=2,点1Y=2,点2X=1,点2Y=1 距离被计算为1,角度被计算为-1。距离应该是1.414,角度应该是-135.000度,所以如果有意义的话,它就像它向上/向下四舍五入一样 using System; using System.Collections.Generic; using System.Linq; using Sys
e、 g.点1X=2,点1Y=2,点2X=1,点2Y=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);
}
}
}
您在上述行中有一个bug。您需要计算:
float deltaY = point2Y - point1Y;
此外,还需要引入计算角度的逻辑。该公式将在下面讨论:
它不会显示小数点
您得到的输出是什么,您希望得到什么?点1x=2,点1y=2,点2x=1,点2y=1。距离计算为1,角度计算为-1。距离应为1.414,角度应为-135.000度,因此,如果有意义的话,它类似于向上/向下舍入它们……不,它是doesn没有意义。我的数学足以做到这一点,我的问题是:你得到的输出是什么,你期望得到什么?
显示具体的示例…你有point2Y-point2X
…使用调试器会显示你得到了一个错误的数字,并且你可以检查原因。啊,这很有意义。解决了它!谢谢!我如何显示数据输出到小数点后三位?@SamFarr:使用:控制台.WriteLine(“点之间的角度是:{0:N3}”,角度);
@LutzL:你说得对;谢谢你指出这一点。我已经更正了答案。明白了,再次感谢:)
float deltaY = point2Y - point1Y;
var angle = Math.Atan2(deltaY, deltaX) * 180 / Math.PI;
Console.WriteLine("The angle between the points is: {0}", angle);