c++ - 如何在 C++ 中使用 arctanx 函数修复此错误
问题描述
我的老师最近给了我一个关于一些称为 arctanx 公式的数学方程/公式的问题。问题是:
According to the Arctanx(x) = x - ((x ^ 3) / 3) + ((x ^ 5) / 5) - ((x ^
7) / 7) + ...and π = 6 * arctanx(1 / sqrt(3)), Create function arctanx(x)
, and find pi when the last "number"(like this ((x ^ y) / y)) is right before
and bigger than 10 ^ -6, or you can say that no "number" can be smaller than
that number without being smaller than 10 ^ -6.
我试图将其编码出来,但其中有一个错误。
# include<iostream>
# include<math.h>
using namespace std;
float arctanx() {
long double pi = 3.1415926535897;
int i = 0; // 0 = +, 1 = -
float sum = 0;
float lsum;
for (int y = 1; y < pi; y += 2) {
if (lsum > 0.000001) {
if (i == 0) {
lsum = pow(1 / sqrt(3), y) / y;
sum += pow(1 / sqrt(3), y) / y;
i++;
} else if (i == 1) {
lsum = pow(1 / sqrt(3), y) / y;
sum -= pow(1 / sqrt(3), y) / y;
i--;
}
} else {
break;
}
}
sum = sum * 6;
return sum;
}
int main() {
cout << arctanx();
return 0;
}
它应该有一个不等于零的数字的输出,但我从运行它得到了 0。
解决方案
您的程序具有未定义的行为,因为您float lsum;
在比较中使用了未初始化的if (lsum > 0.000001)
。在您的情况下可能发生的情况是lsum
恰好小于或等于0.000001
并且您for
立即break
s 没有做任何导致您的函数返回的事情,0 * 6
这显然是0
.
推荐阅读
- jquery - 使用 jQuery + HTML 进行网站搜索
- linux-kernel - 如何实现带阻塞的字符设备?
- python - 检查熊猫数据框的最后一行是否满足条件的最佳方法是什么?
- reactjs - 如何从对回调 URL 的响应中提取数据?
- azure-functions - 使用 CLI 创建 Azure Function 项目
- typescript - 谷歌地图没有显示 Javascript Ionic 4
- ssl - 获取剩余有效期的 SSL 证书的证书错误
- spring - JUnit 测试:NoSuchBeanDefinitionException:没有符合条件的 bean 类型
- google-cloud-run - ENV 变量中的 Google Cloud Run 和 JSON
- php - 致命错误:存在时找不到类“conn”