Другие языки программирования и технологии

Алгоритм цикла с неизвестным числом повторений. C++.

Разработать программу для вычисления указанной функции разложением ее в ряд для заданных аргументов с заданной точностью с использованием оператора цикла с предусловием и оператора цикла с постусловием в c++. Функция sin x. X(-1:1).
SA
Samir Aliyev
128
#include <iostream>
#include <iomanip>
using namespace std;
double fact(unsigned n) {
auto m = 1.;
while (n) {
m *= n;
--n;
}
return m;
}
int main() {
const auto eps = 1e-15;
cout << "x: ";
double x;
cin >> x;
auto i = 1U;
auto step = 1U;
auto sum = .0;
auto n = x * 2;
while (true) {
auto m = pow(x, i) / fact(i);
sum += step & 1? m : -m;
++step;
i += 2ULL;
if (fabs(fabs(m) - fabs(n)) < eps) break;
n = m;
}
cout << fixed << setprecision(15)
<< "sum x: " << sum << '\n'
<< "sin x: " << sin(x) << '\n';
system("pause");
}
Роман Рыленков
Роман Рыленков
59 822
Лучший ответ
//Цикл с предусловием.
#include "stdio.h"
#include "conio.h"
#include "math.h"

int main()
{
float x = 0.5;
float eps = 0.001;

float yp = 1;
float y = 0;
int sign = 1;
int f = 1;

int i = 1;
while (fabs(y - yp) > eps)
{
f *= i;
if (i % 2 != 0)
{
yp = y;
y += sign * x / f;
sign *= -1;
}
x *= x;
i += 1;
}

printf("%.6f", y);
_getch();

return 0;
}

//Цикл с постусловием
#include "stdio.h"
#include "conio.h"
#include "math.h"

int main()
{
float x = 1;
float eps = 0.000001;

float yp = 1;
float y = 0;
int sign = 1;
int f = 1;

int i = 1;
do
{
f *= i;
if (i % 2 != 0)
{
yp = y;
y += sign * x / f;
sign *= -1;
}
x *= x;
i += 1;
} while (fabs(y - yp) > eps);

printf("%.6f", y);
_getch();

return 0;
}