Hey all,
Since I am new to this forum I better intorduce myself first. Well, I plan to take C++ in June, but seeing it as being my weakness zone earlier on, I wanna train while I've got the chance. So, I'm studying on my own at home since uni doesn't start until summer, and I try to attempt a few questions. I'm gonna make a few topics so hope you all don't mind.
Here is my first problem and I'll show you how I've worked this out.
The value e^x can be approximated by the sum
1 + x + x^2/2! + x^3/3! + … + x^n/n!
Write a program that takes a value x as input and outputs this sum for n taken to be each of the values 1 to 100. The program should also output e^x calculated using the predefined function exp. The function exp is a predefined function such that exp(x) returns an approximation to the value ex. The function exp is in the library with the header file cmath. Your program should
repeat the calculation for new values of x until the user says she or he is through. 100 lines of output might not fit comfortably on your screen. Output the 100 output values in a format that will fit all 100 values on the screen. For
example, you might output 10 lines with 10 values on each line.
Okay, so there's basically three parts to this: first get the 100 values, then make them fit on the screen properly, and finally, to ask the user if he or she wants to repeat the calculation for another value of x.
Thusfar, I've done the first 2 things : get the 100 values and then display them in a 10 x 10 grid. I can show you guys my source code. Its as follows:
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
double x; //value input by the user
int i=1,counter=0;; /*counter from 1-100 is counter, i will be used to display text in an
array */
double fact=1; //factorial
double ex=0; //this stores the answer for ex
cout << "This program will take a value x from you and will use it to find the";
cout << " approximation value of the expression e^x." << endl;
cout << "Please enter any real number value for x" << endl;
cin >> x; //takes the value x from the user
cout << "Displaying all values from x and entering into the equation" << endl;
while(counter<=100)
{
ex += pow(x,counter)/fact; //calculation for ex
counter++; //increment counter
fact*=counter; //calculation for factorial (counter!)
cout<<ex<<"\t";
if(i%10==0)
cout<<endl;
i++;
}
cout << "The calculated value for counter = 100 is "<<ex<<endl;
cout << "The predefined value is " << exp(1) << endl;
system ("pause");
return 0;
}
My questions now:
1. Is this correct thusfar?
AND
2. How do I modify the loop or add a loop so that the user can repeat the calculation with new values of x? I'm kinda stuck on that one..... if someone can modify my code I'd be grateful.