how to write the coding for cosine rule in c++?

Ask the user to insert the length of two sides (b and c) of a triangle and the angle between them in degree (α), compute and print the length of the third side, a, by using this formula
a^2 = b^2 + c^2 - 2bc (cos (α))
(Note: To use the cosine function(cos), the angle must be in radians instead of degrees. To convert an angle from degree to radians, multiply the angle by π/180)

Sounds like an interesting assignment.

Also sounds pretty straight forward. What part is giving you difficulty?
my solution is:



#include <iostream>
#include <cmath>
using namespace std;

double b,c,degree,radians,a2;
const float PI = 3.142;

int main ()
{
cout<<"Please insert your length b & c "<<endl;
cin>>b>>c;
cout<<"Please input your angle between them in degree "<<endl;
cin>>degree;


radians = (degree*PI/180);
a2 = pow(b,2)+ pow(c,2) - (2*b*c*cos(radians));

cout<<"Your answer is "<<a2<<endl;

return 0 ;

ANY ERROR IN MY CODING? I CAN'T GET THE RIGHT ANSWER ACCORDING TO MY CALCULATION
a2 is a squared, right?

The answer you want is a, not a squared. So you need to get the square root.

There's a sqrt function for that.
yup, a2 is squared. but if i want the answer in a^2 ,then the answer is not the same as i calculated manually.
The value of your PI is "incorrect"... are you using the same value?

if you use for a trace

b= 2
c= 3
angle = 60º
cos(60º) = 0,5

radians=60*3,142/180
radians= 1,04733333...

cos(radians) = 0,49988...

a^2 = 4 + 9 - (2*2*3*cos(60))
a^2 = 13 - (12*0,5)
a^2 = 13 - 6
a = Sqrt(7)
a= 2,64575131

It works if you add the Sqrt of A value


1
2
3
4
5
6
7
8
radians = (degree*PI/180);
a2 = pow(b,2)+ pow(c,2) - (2*b*c*cos(radians));

cout<<"Your answer is "<<a2<<endl;

return 0 ;

ANY ERROR IN MY CODING? I CAN'T GET THE RIGHT ANSWER ACCORDING TO MY CALCULATION 


yes
a2= sqrt(a2);

before the cout<<..
thx you all..
Topic archived. No new replies allowed.