Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
лекции 1 семестр.doc
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
1 Мб
Скачать
☆

1) Цикл с предусловием

while (B) C;

Пустой цикл

Бесконечный цикл

while (B)

{

C1;C2;C3;

}

2) Цикл с постусловием

do C while ( B)

Пример 1

С помощью цикла while вычислить

y=1+2+3+..+n

y=∑in=1i

# include <iostream.h>

void main()

{ int i ,y, n;

cout<<”Enter n=”;

cin>>n;

y=0;

i=1;

while (i<=n) { y=y+i;

i++;

}

cout<<”y=”<<y<<endl;

}

С помощью цикла do while вычислить

y=1+2+3+..+n

# include <iostream.h>

void main()

{ int i ,y, n;

cout<<”Enter n=”;

cin>>n;

y=0;

i=1;

do { y=y+i;

i++;

}

while (i<=n);

cout<<”y=”<<y<<endl;

}

Пример 2

y=1/1!+1/2!+1/3!+…1/n!

y=y+1/f - тип double

# include <iostream.h>

void main()

{

int i ,f, n;

double y;

cout<<”Enter n=”;

cin>>n;

y=0;

i=1;

f=1;

while (i<=n)

{f=f*i;

y=y+(double)1/f;

i++;

}

cout<<”y=”<<y<<endl;

}

Пример 3

Вычислить y=sin(x)

sin (x) =x -x3/3!+x5/5!-x7/7!+…

sin( x) = ∑0∞ (-1)i x2i+1 / (2i+1)!

1 способ

step=x

znak=1

fact=1

y=y+ step*znak/fact

# include <iostream.h>

# include <math.h>

void main()

{

int i, n, fact, znak;

double y,x,step;

cout<<”enter x=”;

cin>>x;

cout<<”enter n=”;

cin>>n;

y=x;

znak=1;

step=x;

factorial=1;

for ( i=1;i<=n;i++)

{

znak=-znak;

step=step*x*x;

factorial=factorial*2*i*(2*i+1);

y=y+znak*stepen/fact;

}

cout<<”y=”<<y;

cout<<”sin(x)=”<<sin(x);

}

2 способ (универсальный для всех рядов )

y= x-x3/3!+x5/5!-x7/7!+…

y=∑0∞ (-1)i x2i+1 / (2i+1)!= ∑0∞ti

ti=ti-1*p

p= ti/ ti-1= ((-1)i x2i+1 / (2i+1)!)/ ((-1)i-1 x2i-1 / (2i-1)!)= -x2/2*i*(2*i+1)

# include <iostream.h>

void main()

{

double y, x, t;

int i, n;

cout << ”enter x=”;

cin >> x;

cout << ”enter n=”;

cin >> n;

y=x;

t=x;

for ( i=1;i<=n;i++)

{

t= -t*x*x/((2*i+1)*2*i)

y=y+t;

}

cout << ”y=” << y;

}

Возможные варианты

while- вариант

# include <iostream.h>

# include <math.h>

void main()

{

const double eps=0.001;

double y, x, t;

cout << ”enter x=”;

cin >> x;

y=0;

t=x;

int i=1;

while (fabs(t)>eps)

{

y = y+t;

t = -t*x*x/((2*i+1)*2*i);

i++;

}

Cout << ”y=” << y;

}

2) При помощи цикла for

for (int i=1; fabs(t)>eps; i++)

{

t= -t*x*x/((2*i-1)*2*i)

y=y+t;

}

Пример 4

Вычислить косинус

Cos(x)=∑i∞ (-1)i x2i / 2i!

p = -x2 / ((2*i+1)*2*i)

# include <iostream.h>

void main()

{double y, x, t; int n;

int n;

cout<<”enter x=”;

cin>>x;

cout<<”enter n=”;

cin>>n;

y=x;

t=x;

for (int i=1;i<=n;i++)

{

t= -t*x*x/((2*i-1)*2*i)

y=y+t;

}

cout<<”y=”<<y;

}

Лекция №5

Преобразование типа переменной в программе.

Операторы перехода