#include <iostream> using namespace std; int J(int h) { int p; for(int i=1;i<=h;i++){ p*=i; } return p; } double sin(double x) { double s=0.0; double t=x; for(int i=0;i<4;i++){ s+=t/J(i*2+1); t=-t*x*x; } return s; } int main() { double n,m; double PI=3.14; cin>>n; m=(n*PI)/180; cout<<sin(m); 这串代码有啥问题 }
时间: 2024-01-22 08:04:17 浏览: 28
这段代码缺少了一个右括号,应该在最后一行的cout语句后面加上右括号。此外,J函数中的p没有初始化,需要将其初始化为1,否则会出现未定义的行为。
正确的代码如下:
```c++
#include <iostream>
using namespace std;
int J(int h) {
int p = 1;
for(int i = 1; i <= h; i++) {
p *= i;
}
return p;
}
double sin(double x) {
double s = 0.0;
double t = x;
for(int i = 0; i < 4; i++) {
s += t / J(i * 2 + 1);
t = -t * x * x;
}
return s;
}
int main() {
double n, m;
double PI = 3.14;
cin >> n;
m = (n * PI) / 180;
cout << sin(m);
return 0;
}
```
此外,PI的值应该使用更精确的常量M_PI(定义在cmath库中),如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int J(int h) {
int p = 1;
for (int i = 1; i <= h; i++) {
p *= i;
}
return p;
}
double sin(double x) {
double s = 0.0;
double t = x;
for (int i = 0; i < 4; i++) {
s += t / J(i * 2 + 1);
t = -t * x * x;
}
return s;
}
int main() {
double n, m;
cin >> n;
m = (n * M_PI) / 180;
cout << sin(m);
return 0;
}
```
这样可以获得更准确的PI值。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)