C++ "Building a series to solve a function"为什么我的近似值不对?

标签 c++ c function built-in

所以我的问题主要是指我的输出。我偏离了 atan(x) 的“真实”值,无论它是什么。我知道这一定很简单,我做错了什么?

Please enter the number you would like to apply arctan to as tan^(-1)*(x)
remember, x cannot be greater than 1 or less than negative 1:.5

The approx arctan of 0.5000 is 0.4794
The true value arctan of 0.5000 is 0.4636

Press any key to continue . . .

#include <cstdlib>
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;

    int main()
    {
        double sum = 0.0, x, denom, term, z;
        int n, sign = -1;
        char again;
    
        do
        {
            cout << "Please enter the number you would like to apply arctan to"
                << " as tan^(-1)*(x) \nremember, x cannot be greater than 1 or less than negative 1:";
            cin >> x;
            cout << endl;
            while (x > 1 || x < -1)
                {
                    cout << "Try again, the domain for arctan is ( -1 < x < 1): ";
                    cin >> x;
                    cout << endl;
                }
    
            if (x > -1 && x < 1)
                {   
                    for (n = 0; n < 19; n++)
                        {
                            sign = sign * (-1);
                            z = (n * 2) + 1;
                            if (n == 0)
                                denom = 1.0;
                            else
                                denom = denom*(2*n)*(2*n+1);
                            term = sign*pow(x, z)/denom;
                            sum = sum + term;
                        }
                }
    
            cout << fixed << setprecision(4) << "The approx arctan of " << x << " is " << sum << endl;
            cout << "The true value arctan of " << x << " is " << atan(x) << endl << endl;
    
            cout<<"Press Enter";
            cin.get();
            cin.ignore();
            cout << endl;
    
            cout << "Would you like to continue (Y/N)?";
            cin >> again;
            cout << endl;
        }
        while (again == 'Y' || again == 'y');
    
        return 0;
    }  

最佳答案

您的泰勒扩展代码是错误的。

替换denom = denom*(2*n)*(2*n+1);denom = 2*n+1;它有效

关于C++ "Building a series to solve a function"为什么我的近似值不对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26022959/

相关文章:

c++ - opencv - 预测球的碰撞

c++ - CreateFile 打开在另一个终端 session 中创建的 MS-DOS 设备

c - 发送 ICMP ping

arrays - 快速从数组中获取值并使用递归函数将它们放入另一个数组

c++ - 为什么我们使用函数原型(prototype)?

javascript从数组中删除项目

c++ - 在类C++中的并集内初始化数组

c++ - 为什么在 C++ 中说 "can' t find constructor?

c++ - 使用 avr-gcc 编译器/链接器对链接 avrfix 库中函数的 undefined reference

c - void 指针 = int 指针 = float 指针