Reputation: 35
So i have a problem with decimal type . My task : Description There are a point and a line in 3D space. Find the distance between them. Input:
Nine reals, the 3D coordinates of:
The given point.
The point on the line.
The direction vector of the line.
The length of the direction vector is greater than 1e-8. Output: A real, the distance between the given point and the line. Example:
Input: 1.0 1.0 1.0 2.0 1.0 1.0 0.0 0.0 1.0 Output: 1.0 My code:
static void Main(string[] args)
{
var input = Console.ReadLine();
var numbers = input.Split(' ').Select(x => decimal.Parse(x)).ToArray();
var m0 = new[] {numbers[0],numbers[1],numbers[2] };
var m1 = new[] { numbers[3], numbers[4], numbers[5] };
var s= new[] { numbers[6], numbers[7], numbers[8] };
decimal[] m1m0=new decimal[3];
for(int i =0;i<3;i++)
{
m1m0[i] = m1[i] - m0[i];
}
decimal[] m1m0s = new decimal[3];
m1m0s[0] = m1m0[1] * s[2] - m1m0[2] * s[1];
m1m0s[1] = m1m0[2] * s[0] - m1m0[0] * s[2];
m1m0s[2] = m1m0[0] * s[1] - m1m0[1] * s[0];
var d = GetAbs(m1m0s[0], m1m0s[1], m1m0s[2]) / GetAbs(s[0], s[1], s[2]);
Console.WriteLine((decimal)d);
}
static decimal GetAbs(decimal a , decimal b , decimal c )
{
var d = a * a + b * b + c * c;
double e = (double)d;
var temp= Math.Sqrt(e);
decimal sqrt = Convert.ToDecimal(temp);
return sqrt ;
}
My result of program : input 1.0 1.0 1.0 2.0 1.0 1.0 0.0 0.0 1.0 output 1
I need my result to be with a floating point, even if I get an integer type .Output need to be 1.0 or 2.0 ,but not a 1 or 2 .
Upvotes: 0
Views: 95
Reputation: 35733
Console.WriteLine(d.ToString("0.0#######"));
format string "0.0#######"
cuts all trailing zeroez but guarantees at least one digit after decimal point.
possible input and ouput:
Math.Sqrt(2);
1.41421356
Math.Sqrt(0.02);
0.14142136
Math.Sqrt(1);
1.0
Math.Sqrt(0.0001);
0.01
Upvotes: 1
Reputation: 2540
Since you want a decimal point only if value is a whole number and preserve the digits if it a fraction do it as below -
if (d % 1 == 0)
{
Console.WriteLine(String.Format("{0:0.0}", d));
}
else
{
Console.WriteLine(d);
}
Upvotes: 0