hello there, I was recently asked to code the sine of a given value using the Taylor series.
FYI before getting mad at me:
Yes, it was an assignment given to me.
I don't expect anyone to give me just a code.
I did this code from scratch in my head!
I'm having a hard time getting the twist of nested loops, writing this code took me hours just to figure out the right way to implement it.
When comparing with some classmates, I realized my code was actually cleaner than most of them.
SO my question is: can anyone give me some tips on how should I visualize those kinds of problem? when do we know it is necessary to have nested loops? could I have written a code giving the same result using only 1 loop?
thank you very much, kind sirs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double x=1;
double y = 1;
double sum = 0;
double fact = 1;
double sign = -1;
cout << "please enter a value of x to calculate its sine";
cin >> x;
for (int i = 1; i < 100; i += 2)
{
fact = 1;
for (int j = 1; j <= i ; j++)
{
fact *= j;
}
sum += sign*(-1)*(pow(x, i)) / fact;
sign *= -1;
}
cout << "\n\n\n" <<"SINE("<<x<<") = "<< sum << endl;
return 0;
}
}
|