首页 > 解决方案 > 如何在 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。

标签: c++pi

解决方案


您的程序具有未定义的行为,因为您float lsum;在比较中使用了未初始化的if (lsum > 0.000001)。在您的情况下可能发生的情况是lsum恰好小于或等于0.000001并且您for立即breaks 没有做任何导致您的函数返回的事情,0 * 6这显然是0.


推荐阅读