I'm currently in my first semester learning how to program in C++ and i'm running into a problem trying to make a formula to calculate the following formula:
1 + 1/1! + 1/2! + 1/3! + 1/4!...+ 1/n!
Where "n" is the user input number to calculate up to.
So far what i have completed is split up into 3 files: FactorialMoore.h, FactorialMoore.cpp, DriverMoore.cpp
// FactorialMoore.h
// Created by Travis Moore on October 14th, 2008
// CSCI-40 T,TH 11:00AM - 12:15pm LAB TH 8:00AM - 9:50AM
// Professor Shih-Hsi "Alex" Liu
class Factorial
{
public:
void solveEquation();
private:
};
// FactorialMoore.cpp
// Created by Travis Moore on October 14th, 2008
// CSCI-40 T,TH 11:00AM - 12:15pm LAB TH 8:00AM - 9:50AM
// Professor Shih-Hsi "Alex" Liu
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
}
endResult = static_cast< double >( currentTotal ) + 1;
cout << "The answer to the formula with your number provided is:\n" << fixed << endResult << endl;
}
// DriverMoore.cpp
// Created by Travis Moore on October 14th, 2008
// CSCI-40 T,TH 11:00AM - 12:15pm LAB TH 8:00AM - 9:50AM
// Professor Shih-Hsi "Alex" Liu
#include "FactorialMoore.h"
int main()
{
Factorial myFactorial;
myFactorial.solveEquation();
return 0;
}
I realize this isn't the most difficult question on the forum boards but getting the formula to work has been very frustrating for me. What i'm really looking for is some explanation of how to get the factorial to work correctly in C++ more than i am an answer.
terminationNumber is declared after being used.
There's a missing semicolon on "currentTotal = 1 / factorialTotal".
1/factorialTotal should be added, not assigned, to the total.
Also, there are design problems that don't affect the result, but that shouldn't be there.
}
endResult = static_cast< double >( currentTotal ) + 1;
cout << "The answer to the formula with your number provided is:\n" << fixed << endResult << endl;
Which should look like:
while ( counter <= terminationNumber )
{
factorialTotal *= counter;
currentTotal + 1 / factorialTotal;
counter++;
}
endResult = static_cast< double >( currentTotal ) + 1;
cout << "The answer to the formula with your number provided is:\n" << fixed << endResult << endl;
I think where i am getting hung up in my comprehension of the problem is that the line:
currentTotal + 1 / factorialTotal;
needed to be assigned to a variable in order to be saved which is why i had originally put:
currentTotal = 1 / factorialTotal
Don't i need to make sure that "currentTotal + 1 / factorialTotal;" is assigned to a variable? Otherwise where does this statement get stored?
(and thank you again for correcting the addition that needed to take place)
double result = 1.0;
int n = 5;
int total = 0;
for (int i = 1; i <= n; ++i) {
int total = 1;
for (int j = 2; j <= i; ++j) {
total *= j;
}
result += 1 / total;
}
Have a look at that and see if that is what your trying to achieve.