格式化C ++程序的输出

时间:2015-12-01 03:42:03

标签: c++

我已经为问题编写了大部分代码,但它确实有效。我只是不确定如何格式化输出。

问题:设计和开发用于在delta <= 0.000001

时计算e(n)的C ++程序
e(n-1) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n-1)!

e(n) = 1 + 1/1! + 1/2! + 1/3! + 1/4! + … + 1/(n)!

delta = e(n) – e(n-1)

您没有对该计划的任何输入。你的输出应该是这样的:

  

N = 2e(1)= 2e(2)=2.5δ= 0.5

     

N = 3e(2)= 2.5e(3)=2.565δ= 0.065

    #include <iostream>
using namespace std;

//3! = 3 * 2!
//2! = 2 * 1! 
//1! = 1
int factorial(int number) 
{
    //if number is <= 1, return 1
    if (number <= 1)
    {
        return 1;
    }
    // otherwise multiply number by factorial(number - 1)
    else
    {
            //otherwise multiply number by factorial(number - 1) and return it
        int temp = number * factorial(number - 1);
        cout << "factorial of " << number << " = " << temp << endl;
            return temp;
    }
}

double sumOfFactorials(int n) 
{
    double sum = 0;
    //loop from 1..n, adding the factorial division to a sum
    for (int i = 1; i <= n; i++)
    {
        double dividedValue = 1.00000 / factorial(i);
        cout << fixed;
        sum = sum + dividedValue;
    }
    return sum;
}

/**
* Compute the sum of 1 + ... + 1/(n!)
* input number: 1
* output number: 1 + ... + 1/(input!)
*/
double e(int n) 
{
    double value = 1 + sumOfFactorials(n);
    return value;
}

int main()
{
    cout << "e:" << e(3) << endl; // 1 + sumOfFactorials(3)
    cout << "sumOfFactorials: " << sumOfFactorials(3) << endl; //0 + 1/1! + 1/2! + 1/3!
}

1 个答案:

答案 0 :(得分:0)

您拥有正确的代码,您只需要格式化输出。只需修改main()方法即可。这是你可以尝试的片段。

注意:答案的精确度有误,我想你可以纠正它。

PS:请取消注释调试cout行。

int main()
{


for(int i = 2; i<4; i++){

    double en_1 = e(i-1);
    double en = e(i);
    double delta = en - en_1;

    cout << "N = "<<i;
    cout << " e("<< (i-1) <<") = " << en_1;
    cout << " e("<< (i) <<") = " << en;

    cout << "delta = " << delta;
    cout << "\n";
}   



}