编写一个同时支持角度和弧度作为参数的计算sin值的函数。
时间: 2024-05-08 07:17:27 浏览: 9
下面是一个Python实现的例子:
```python
import math
def sin(x, unit='radian'):
if unit == 'degree':
x = math.radians(x)
return math.sin(x)
```
该函数接受两个参数:x和unit。x是角度或弧度,unit是一个字符串,指示x是角度还是弧度。如果unit是'degree',则将x从角度转换为弧度。最后,该函数返回x的sin值。
示例用法:
```python
print(sin(45)) # 0.7071067811865475 (默认为弧度)
print(sin(45, 'degree')) # 0.7071067811865475
print(sin(math.pi/4)) # 0.7071067811865475
```
相关问题
用C语言编写一个计算SIN函数的代码
下面是一个简单的用C语言编写计算SIN函数的代码:
```c
#include <stdio.h>
#include <math.h>
double sin(double x);
int main()
{
double x, result;
printf("请输入x的值(以弧度为单位):");
scanf("%lf", &x);
result = sin(x);
printf("sin(%lf) = %lf\n", x, result);
return 0;
}
double sin(double x)
{
double result = 0;
int i;
for (i = 0; i < 10; i++) {
result += pow(-1, i) * pow(x, 2 * i + 1) / tgamma(2 * i + 2);
}
return result;
}
```
这个程序使用了 math.h 中的 pow 和 tgamma 函数,分别用于计算幂次和阶乘。这个实现并不是特别高效,但是足以演示如何计算SIN函数。
编写一个计算三角函数值的python编程
下面是一个计算三角函数值的Python程序:
```python
import math
# 输入角度值
angle = float(input("请输入角度值:"))
# 将角度值转换为弧度值
rad = math.radians(angle)
# 计算三角函数值
sin = math.sin(rad)
cos = math.cos(rad)
tan = math.tan(rad)
cot = 1 / tan
sec = 1 / cos
csc = 1 / sin
# 输出结果
print("sin({}) = {}".format(angle, sin))
print("cos({}) = {}".format(angle, cos))
print("tan({}) = {}".format(angle, tan))
print("cot({}) = {}".format(angle, cot))
print("sec({}) = {}".format(angle, sec))
print("csc({}) = {}".format(angle, csc))
```
该程序首先要求用户输入一个角度值,然后将其转换为弧度值,并使用Python中的math库计算其对应的正弦、余弦、正切、余切、正割和余割值,最后输出结果。
注意:输入的角度值应该是一个实数,而不是一个整数。