Implement Mathematical Function
Write a C++ program to implement/compute the following mathematical
function f(x) for a positive integer x:
1/2 + 2/3 + 3/4 + .... x/x+1
Help.
1 2 3 4 5 6
|
float exponential(int n, float x)
{
float sum = 1.0f; // initialize sum of series
for (int i = n - 1; i > 0; --i )
sum = 1 + x * sum / i;
|
all I got so far
Shouldn't x be an int ?
What is n for ?
garza07, are you sure they don't want you to literally output the string "1/2 + 2/3 +...." rather than a single float result?
you are right let me fix my program
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
using namespace std;
int main()
{
int x = 0;
double result = 0;
cout << "Enter value of x:";
cin >> x;
for(int i = 1; i <= x; i++)
result += ((double)i / (double)(i + 1));
cout << "Result = " << result;
return 0;
}
|
that's more like it, though you probably want to initialize your result to 1.0, not 0.0, if indeed you want 1 + 1/2 ...
Here's one that also prints the string:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
using namespace std;
void Series(int x)
{
float sum = 1.0f;
cout << "1";
for(int denom=2; denom<=x+1; ++denom)
{
cout << " + ";
cout << denom-1 << "/" << denom;
sum += (denom-1)/(float)denom;
}
cout << " = " << sum << endl;
}
int main()
{
for (int x=1; x<=10; ++x)
Series(x);
return 0;
}
|
1 + 1/2 = 1.5
1 + 1/2 + 2/3 = 2.16667
1 + 1/2 + 2/3 + 3/4 = 2.91667
1 + 1/2 + 2/3 + 3/4 + 4/5 = 3.71667
1 + 1/2 + 2/3 + 3/4 + 4/5 + 5/6 = 4.55
1 + 1/2 + 2/3 + 3/4 + 4/5 + 5/6 + 6/7 = 5.40714
1 + 1/2 + 2/3 + 3/4 + 4/5 + 5/6 + 6/7 + 7/8 = 6.28214
1 + 1/2 + 2/3 + 3/4 + 4/5 + 5/6 + 6/7 + 7/8 + 8/9 = 7.17103
1 + 1/2 + 2/3 + 3/4 + 4/5 + 5/6 + 6/7 + 7/8 + 8/9 + 9/10 = 8.07103
1 + 1/2 + 2/3 + 3/4 + 4/5 + 5/6 + 6/7 + 7/8 + 8/9 + 9/10 + 10/11 = 8.98012 |
thank you so much
1 2 3 4 5 6 7 8 9
|
#include <iostream>
using namespace std;
double series( unsigned x ) { return x ? series( x - 1 ) + x / ( x + 1.0 ) : 0; }
int main()
{
for ( unsigned x = 1; x <= 10; x++ ) cout << x << ": " << series( x ) << '\n';
}
|
1: 0.5
2: 1.16667
3: 1.91667
4: 2.71667
5: 3.55
6: 4.40714
7: 5.28214
8: 6.17103
9: 7.07103
10: 7.98012 |
Topic archived. No new replies allowed.