help in functions

Please help me in this problem.

Rewrite the following program using the following functions:
1) double SINX(double x, int m)
2) double Fact(int n)
3) void powx(double x, int n, double y); y= x to power n

Notes:
- Don't use the built in pow function.
- Don't use powx for (-1) to power n.
- In the main program you will call the function SINX and it will call the other two fuctions.
- Form your output to 3 decimal places and use width 9 for each number.

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double sinx=0,fact,x;
int m;
cout<<"Enter x and m:";
cin>>x>>m;
for (int n=0; n<=m; n++)
{
fact=1;
for (int i=1; i<=2*n+1; i++)
fact*=i;
double term;
term=pow(-1.0,n)*pow(x,2*n+1)/fact;
sinx+=term;
}
cout<<"The value of sin"<<x<<endl;
cout<<"computed="<<sinx<<endl;
cout<<"Built-in="<<sin(x)<<endl;
return 0;
}
First and foremost, use code tags. http://cplusplus.com/articles/z13hAqkS/

Second, we don't do homeworks for others. If you can rephrase your problem so it is clear as to where you need help, and provided that where != EVERYWHERE, then we'll gladly lend a hand.
If Fact is a Factorial function you could impress you Prof by using recursion.

The first thing you need to do is grab a piece of paper and write down the steps to accomplish the goal. If you don't know what the steps are then you have no business coding.


Just using plain English I came up with this :

multiply x times itself n number of times and set it equal to y

But then after thinking about it I realized that since n is the number I start with I would only
multiply by n-1 versions of itself.

So, 4 cubed is n x n x n. So since I already have n I only need 2 extra versions of itself, not 3 or then I would be calculating 4 to the 4th power.

Then I convert to code, or attempt to.

1
2
3
4
5
6
7
8
9
10
        // actual code
	void powx(double x, int n, double y) {
              double tmp = x;
	      for(int i = 0; i < n-1; i++) {
		   y = tmp * x;
	           tmp = y;
	      }
    
        cout << y << endl;
        }


This is just a sample and will not account for (Don't use powx for (-1) to power n.), whatever that means. I am fairly bad at Math as well even though I have a minor in Applied Mathematics so I'm sorry if my explanation was poor.
Last edited on
Topic archived. No new replies allowed.