我正在编写一个程序,读取三角形的每一边,计算其度数并确定它是直角三角形,斜角三角形还是三角形。
我计算余弦然后从余弦中找出度数:the cos equation
以下是代码:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
int a,b,c;
double val, cA, cB, cC, angleA, angleB, angleC;
int main()
{
printf("Input the length of each side!");
printf("\na: ");
scanf("%d", &a);
printf("\nb: ");
scanf("%d", &b);
printf("\nc: ");
scanf("%d", &c);
//calculating the cosine
cA = ((b*b)+(c*c)-(a*a))/(2*b*c);
cB = ((a*a)+(c*c)-(b*b))/(2*a*c);
cC = ((a*a)+(b*b)-(c*c))/(2*a*b);
val = 180.0/PI;
if(cA>=0&&cA<=1){
angleA = acos(cA)*val;
} else{
angleA = 0;
}
if(cB>=0&&cB<=1){
angleB = acos(cB)*val;
} else{
angleB = 0;
}
if(cC>=0&&cC<=1){
angleC = acos(cC)*val;
} else{
angleC = 0;
}
printf("\ncos A= %lf", cA);
printf("\ncos B= %lf", cB);
printf("\ncos C= %lf", cC);
printf("\nAngle A= %lf", angleA);
printf("\nAngle B= %lf", angleB);
printf("\nAngle C= %lf", angleC);
}
我还在尝试计算余弦,但只要我输入三角形的边值,cA,cB,cC只给出零。
cos A= 0.000000
cos B= 0.000000
cos C= 0.000000
如何使cos方程返回正弦的正确值?
答案 0 :(得分:0)
在以下行中:
cA = ((b^2)+(c^2)-(a^2))/(2*b*c);
您在int
上进行计算并将结果保存到double
。这意味着您最终可能会得到8 / 10
之类的中间结果,它只是0
而不是分数。
但更大的问题是^
是XOR
操作,而不是您的想法。使用b*b
或pow(b, 2)
。
答案 1 :(得分:0)
所以我改变了一点来解决除以零结果:
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
double a,b,c;
double val, cA, cB, cC, angleA, angleB, angleC;
int main()
{
printf("Input the length of each side!");
printf("\na: ");
scanf("%lf", &a);
printf("\nb: ");
scanf("%lf", &b);
printf("\nc: ");
scanf("%lf", &c);
//calculating the cosine
cA = ((b*b)+(c*c)-(a*a))/(2*b*c);
cB = ((a*a)+(c*c)-(b*b))/(2*a*c);
cC = ((a*a)+(b*b)-(c*c))/(2*a*b);
val = 180.0/PI;
if(cA>=0&&cA<=1){
angleA = acos(cA)*val;
} else{
angleA = 0;
}
if(cB>=0&&cB<=1){
angleB = acos(cB)*val;
} else{
angleB = 0;
}
if(cC>=0&&cC<=1){
angleC = acos(cC)*val;
} else{
angleC = 0;
}
printf("\ncos A= %lf", cA);
printf("\ncos B= %lf", cB);
printf("\ncos C= %lf", cC);
printf("\nAngle A= %lf", angleA);
printf("\nAngle B= %lf", angleB);
printf("\nAngle C= %lf", angleC);
}
我猜整数输入不起作用,所以我把它改成了双倍。