Reputation: 65
I am studying C# and found this practice problem:
Write a program that calculates the area of a triangle with the following given: the lengths of two sides and the angle between them (hint: side-angle-side)
I know how to find the area of a triangle in C# if I have the base and the height, and I know that there's a way to use the .Cos method in the .Math class in order to get the cosine that I need for my problem. However, my program does not seem to like the syntax that I am using. May I have any advice for how to implement methods in the .Math class in order to solve a geometry problem like this that takes user input for the side, the angle, and the other side?
I know that the formula is c^2 = a^2 + b^2 - 2ab * cos(y) //where y = the degree of the angle
Here is what I have so far, which I think will get across what I am trying to do:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace day_of_the_week
{
class Program
{
static void Main(string[] args)
{
double side1;
double side2;
double angle;
Console.WriteLine("Enter one side length.");
side1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the other side's height.");
side2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the value of the angle.");
angle = Convert.ToDouble(Console.ReadLine());
double thirdside = Program.thirdside(side1, side2);
Console.WriteLine(thirdside);
Console.ReadLine();
}
public static double thirdside(double side1, double side2, double angle)
{
return (side1*side1 + side2*side2 - 2*side1*side2.Cos(angle));
}
}
}
Upvotes: 0
Views: 4484
Reputation: 25972
Note that the area of the triangle is
0.5*side1*side2*sin(toRadians(angle))
if angle
is the angle between side1
and side2
.
Upvotes: 0
Reputation: 3729
Need to specify class. so that is Math.Cos(angle)
. Also use Math.Pow(side1, 2)
to square numbers.
Upvotes: 0
Reputation: 612784
Implement your function with calls to Math.Cos
and Math.Sqrt
, like this:
public static double rad(double deg)
{
return deg * Math.PI / 180;
}
public static double thirdside(double side1, double side2, double angleDeg)
{
double angleRad = rad(angleDeg);
return Math.Sqrt(side1*side1 + side2*side2 - 2*side1*side2*Math.Cos(angleRad));
}
Bear in mind that it is likely that you will want to input the angle in degrees. But Math.Cos
accepts the angle in radians, hence the conversion.
And the code in the question neglected to take the square root of the expression. The code in this answer does so.
Upvotes: 2