Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Robert Kristof, Mateusz Urbanek Task 3
- //This program calculates Cos(x) without use of cmath library
- #include "pch.h"
- #include <iostream>
- using namespace std;
- double Power(double number, int power) {
- if (power == 0) { return 1; }
- else {}
- double Powered = number;
- for (int i = 1; i < power; i++) {
- Powered *= number;
- }
- return Powered;
- }
- double Factorial(double Fact) {
- if (Fact < 0) { return 0; } //Factorial of number less than 0 does not exist
- if (Fact == 0) { return 1; } //Factorial of 0 is always equal to 1
- double Result = 1;
- for (int i = 1; i <= Fact; i++) {
- Result *= i;
- }
- return Result;
- }
- double Cosinus(double x, double y) {
- int True = 1;
- double PreviousX = 1;
- double ResultOfCosine = 0; //Result of Cosinus(x) function
- int Iter = 1;
- while (True == 1) {
- //cout << "Iteration number " << Iter << endl;
- double FirstVariable = Power(-1, Iter);
- //cout << "I did first one " << FirstVariable << endl;
- double SecondVariable = Power(x, 2 * Iter);
- //cout << "I did second one " << SecondVariable << endl;
- double ThirdVariable = Factorial(2 * Iter);
- //cout << "I did third one " << ThirdVariable << endl;
- ResultOfCosine = ((FirstVariable * SecondVariable) / ThirdVariable) + PreviousX;
- //cout << "afterfirst Result" << endl;
- //cout << ResultOfCosine << endl;
- //cout << "Previous " << PreviousX << endl;
- if (((PreviousX - ResultOfCosine <= y) && (PreviousX - ResultOfCosine >= 0)) || ((ResultOfCosine - PreviousX <= y) && (ResultOfCosine - PreviousX >= 0))) {
- True = 0;
- //cout << "Setting True" << endl;
- }
- else { True = 1; }
- PreviousX = ResultOfCosine;
- Iter++;
- }
- cout << "Your cosinus of x is equal to:\t" << ResultOfCosine << endl;
- cout << "Number of iterations is equal to:\t" << Iter - 1 << endl;
- return 1;
- }
- int main() {
- double x0; //x0
- double Acc; //Accuracy
- cout << "Input x0" << endl;
- cin >> x0;
- cout << "What is your accuracy?" << endl;
- cin >> Acc;
- Cosinus(x0, Acc);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement