Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ConsoleApplication2.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- int factorial(unsigned int a)
- {
- if (a== 0)
- return 1;
- else
- {
- unsigned int i = 1;
- unsigned long int sum = 1;
- while (i <= a)
- {
- sum = sum*i;
- i++;
- }
- //cout << sum << "\n";
- return sum;
- }
- }
- int main()
- {
- double xval, yval, eps, sum, sumprev;
- unsigned int i;
- cout << "Enter a value for x: ";
- cin >> xval;
- eps = 0;
- while (eps != 1 && eps != 2 && eps != 3)
- {
- cout << "\nChoose a value for epsilon for computing sin(x):\n1) 0.1\n2) 0.01\n3) 0.001\n";
- cin >> eps;
- }
- if (eps == 1)
- eps = 0.1;
- else if (eps == 2)
- eps = 0.01;
- else if (eps == 3)
- eps = 0.001;
- sum = 0;
- sumprev = 99;
- i = 0;
- while (abs(sum - sumprev) > eps)
- {
- if (2 * i + 1 > 13)
- {
- cout << "Maximum factorial reached\n"; //Cannot compute factorials over 14 due to size limit of long type.
- sumprev = sum;
- }
- else
- {
- sumprev = sum;
- sum = sum + (pow(-1, i) / factorial(2 * i + 1))*pow(xval, 2 * i + 1);
- cout << "at n=" << i << ", sin(" << xval << ") = " << sum << "\n";
- i++;
- }
- }
- sum = 0;
- for(unsigned int cosLoopI = 0; cosLoopI <= 7; cosLoopI++) //Cannot compute factorials over 14 (2*7) due to size limit of long type.
- {
- sum = sum + (pow(-1, cosLoopI) / factorial(2 * cosLoopI))*pow(xval, 2 * cosLoopI);
- cout << "at n=" << cosLoopI << ", cos(" << xval << ") = " << sum << "\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement