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

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

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

1) y=y+static_coast<double>i / (i+1)

2) y=y+(double) i/(i+1)

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

Break

i=1;

while(1)

{

if(i>10) break;

cout<<”i=”<<i<<”_”;

i++;

}

cout<<endl;

результат работы программы:1_2_3_4_5_6_7_8_9_10

 

Continue

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

{

if (i %2) continue;

cout<<i<<”_”;

}

результат работы программы:2_4_6_8

Goto

С помощью инструкции goto и метки можно организовать

следующий цикл на 100 итераций.

 

i=1;

loop1:

cout<<i<<”_”;

i++;

if (i<=100) goto loop1;

 

 

результат работы программы:1_2_3_4_5_6_7_... _100

 

Оператор switch (переключатель)

switch (выражение) { case константа 1: [список операторов]

case константа 2: [список операторов]

………………………………………….

case константа n: [список операторов]

default: [список операторов]

}

 

 

Задача 1

Простейший калькулятор

 

# include <iostream.h>

void main()

{

int a,b,res;

char op;

cout <<” enter 1 operand:”;

cin>>a;

cout <<” enter sign of operation:”;

cin>>op;

cout <<” enter 2 operand:”;

cin>>b;

bool f=true;

switch (op) {

case ‘+’ : res=a+b; break;

case ‘-‘ : res=a-b; break;

case ‘*‘ : res=a*b; break;

case ‘/‘ : res=(double) a/b; break;

default: cout<<”unknown operator “<<endl;

f=false;

}

if (f) cout<<”result:”<<res<<endl;

}

 

Задача 2

Угадывание числа

 

# include <iostream.h>

# include <stdlib.h>

# include <time.h>

void main()

{

bool t;

int x, y, n, i;

srand (time(0));

x=rand()%10+1;

cout<<” the computer define number in the range 1-10”<<endl;

t=false;

cout<<” Guess the number!!!”<<endl;

cout<< “You must guess the number the computer”<<endl;

cout<<” enter n=”;

cin>>n; //ввод количества попыток

i=1;

while ( i<=n && !t )

 

{

cout<<”enter number”;

cin>>y; //ввод числа пользователем

if (y==x) t=true;

i++;

}

if (t)

{

cout<< “You win!”<<endl;

cout<<” The number of attempts i = ”<<i<<endl;

cout<<”Computer defined number:<<x<<endl;

}

else {

cout<<”Sorry! The computer number =”<<x<<endl;

}

}

 

Задача 3

Определение простого числа

 

true, если число x простое

T=

false, если число x не является простым

 

i=2…..sqrt(x)- возможные делители числа х.

 

Листинг программы

# include <iostream.h>

# include <math.h>

void main()

{

int i,x;

bool t;

cout<<”enter x=”;

cin>>x;

 

if (x<=1) t=false;

else if (x==2) t=true;

else

{

t=true;

for (i=2; i<=sqrt(x) && t; i++)

{

if (x% i==0) t=false;

 

}

}

if (t) cout<< x<<” -prime”<< endl;

else cout<< x<<” - not prime”<< endl;

}

 

Задача 4.

Вывод строчные букв латинского алфавита и их кодировки.

 

 

# include <iostream.h>

void main()

{

char ch;

int i;

for ( ch=’a’;ch<=’z’;ch++ )

cout<<ch<<’ ’; // вывод символов(строчные буквы латинского алфавита)

cout<<endl;

for (i=’a’;i<’a’+26; i++)

cout<<i<<’ ‘; // вывод кода символов

cout<<endl;

 

}

 

 

Задача 5

Число итераций за 1 сек.

Секундомер

 

#include <iostream.h>

#include <stdlib.h>

#include <time.h>

void main()

{

int i, j, k, m;

 

int l=time (0);

int p=1;// число итераций за 1 сек

while (time (0)-l < 1)

{

cout<<time(0)<<':'<<'_';

p++;

// system("pause");

}

cout<<endl<<"p= "<<p<<endl;

// число итераций за 1 сек

cout<<endl;

 

cout<<"hours: minutes: second"<<endl;

for(m=0;m<=24;m++)

for(i=0; i<=59; i++)

for(j=0; j<=59;j++)

for (k=1;k<=100000;k++)// задержка

{

cout.fill('0'); cout.width(2);

cout<<m<<':';

cout.fill('0'); cout.width (2);

cout<<i<<':';

cout.fill('0'); cout.width (2);

cout<<j<<'\r';

}

cout<<endl;

}

Лекция №6

Массивы

а0, а1, а2,…….аn-1

Массив- конечная именованная последовательность элементов

Описание массива в С++:

Тип имя [размер]

Например:

int a[100] или const int N=100;

int a[N];

 

Обращение к элементу массива: а[номер].

Одномерный массив – вектор;

Память для элементов массива выделяется подряд

1234

a- указатель-переменная, которая хранит адрес.

 

Задача 1