#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
double cosin_value( double value );
double sin_value( double value );
double big_degree( double value );
double big_radian( double value );
double x;
double value;
double degree;
double radian;
const double PI = 3.14159;
char choice;
char yes;
int main()
{
cout << "Please enter an angle value => ";
cin >> value;
cout << "Is the angle in Degree or Radian?" << endl;
cout << "\t" << "Type D if it is in Degree" << endl;
cout << "\t" << "Type R if it is in Radian" << endl;
cout << "Your response => ";
cin >> choice; //degree or radian?
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(10);
if (choice == 'D' || choice == 'd')
{
big_degree (value);
cout << " " << "sin(x) = " << "\t" << sin_value(degree) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(degree) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(degree) / cosin_value(degree) << endl;
}
else if (choice == 'R' || choice == 'r')
{
big_radian (value);
cout << " " << "sin(x) = " << "\t" << sin_value(radian) << endl;
cout << " " << "cos(x) = " << "\t" << cosin_value(radian) << endl;
cout << " " << "tan(x) = " << "\t" << sin_value(radian) / cosin_value(radian) << endl;
}
return 0;
}
// Sine,cosine functions
// angle -360<value<360
double sin_value( double value )
{
int count=1;
double sine, num, dem, sign, term;
sine = 0;
sign = 1;
num = value;
dem = count;
while ( count <= 20 )
{
term = ( num / dem );
sine = sine + term * sign;
num = num * value * value;
count = count + 2;
dem = dem * count * ( count - 1 );
sign = -sign;
}
return (sine);
}
double cosin_value( double value )
{
int count = 0;
double cosine, num, dem, sign, term;
cosine = 0;
sign = 1;
num = 1;
dem = 1;
while ( count <= 20 )
{
term = ( num / dem );
cosine = cosine + term * sign;
num = num * value * value;
count = count + 2;
dem = dem * count * ( count - 1 );
sign = -sign;
}
return (cosine);
}
double big_degree( double value )
{
int result;
const int angle = 360;
if (value >= 360 || value <= -360)
{
result = value / angle;
degree = ( value - ( result * angle ) ) * PI / 180;
}
else
{
degree = ( value * PI ) / 180;
}
return (degree);
}
double big_radian( double value )
{
int result;
if (value >= 2 * PI || value <= -2 * PI)
{
result = value / ( 2 * PI );
radian = ( value - ( result* 2 * PI ) );
}
else
{
radian = value;
}
return (radian);
}
我在这里遇到的问题很少:
当我输入 90度或1.5708弧度值时,程序如何显示 tan(x) 无穷大?当我输入90度时,它为cos(x)输出0.0000013268而不是0。
我试图在我的cosin函数中输入此命令,其中如果cos(x)&lt; 0.00001 ,将其设置为零,它可以工作90度但是对于其他值如2.3145弧度, cos(x)值为0而不是-0.677013 。
感谢您的导游!
答案 0 :(得分:4)
使用epsilon值就像你在问题#2中提到的那样。
在if语句中使用cos(x)的绝对值,如abs(cos(x))。
你也可以用double或float表示无穷大。检查此链接。 http://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html
更重要的是,您可能希望阅读这篇名为“每个计算机科学家应该知道浮点算术的内容”的文章 http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
您会注意到浮点运算的每一步都会累积计算错误。