Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                                                                                            
                
        
我已经使用类对象编写了代码,以使用下面给出的级数求和来近似计算e ^ 1的值,但似乎我无法使逻辑正常工作。我尝试将其运行到5个项进行近似计算,但是我的答案是1.2,只有在2.7038左右。

e ^ 1由级数1 + 1/1给出! + 1/2! + 1/3! ...

#include <iostream>
#include <stdlib.h>
using namespace std;

class factorial
{
public:
double loopfactorial ( double y)
    {

        double value;
    for (int a=0; a<=y; a++)
        {
            value=1;

            value = value*a;
        }
        return value;
    }
};


int main()
{
factorial calcu;
int x;
double sum;
cout<<"Enter the number of terms to approximate exponent:"<<endl;
cin>>x;

for (int y=1; y<=x-1; y++)
{
int n = calcu.loopfactorial(y);

sum=1.0;
sum = sum + 1/n;
}

cout<<"The value of e is "<<sum<<endl;
    return 0;
}

最佳答案

为了给以后的读者带来参考和利益,以下是“正确的”代码:

#include <iostream>
#include <cstdlib>

int main()
{
    unsigned int terms;
    if (!(std::cout << "Number of terms: " && std::cin >> terms))
    {
        std::cout << "Error, I did not understand you.\n";
        return EXIT_FAILURE;
    }

    double e = terms > 0 ? 1.0 : 0.0, term = 1.0;
    for (unsigned int n = 1; n < terms; ++n)
    {
        term /= n;
        e += term;    // this is "e += 1/n!"
    }

    std::cout << "e is approximately " << e << "\n";
}


(可以对代码进行简单扩展,以计算任意x的ex。)

关于c++ - 近似e ^ 1时逻辑错误:( ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22869459/

10-11 00:51