МІНІСТЕРСТВО ОСВІТИ І НАУКИ УКРАЇНИ НАЦІОНАЛЬНИЙ УНІВЕРСИТЕТ "ЛЬВІВСЬКА ПОЛІТЕХНІКА"
Кафедра інформаційних систем та мереж
Лабораторна робота №1
на тему
СТРУКТУРА, ВИКОНАННЯ ТА ВІДЛАГОДЖЕННЯ ПРОГРАМ В ІНТЕГРОВАНОМУ СЕРЕДОВИЩІ BORLAND C++
Львів-2016
Мета роботи: ознайомитись із середовищем Borland C++ 3.1, вивчити способи запису програм на мові Сі, ознайомитись з основними конструкціями мови Сі. Метою роботи є вивчення призначення, правил побудови та застосування засобiв препроцесорного опрацювання текстів програм на мовi Сі.
Перший рівень
Для першого рівня для всіх студентів незалежно від їх номера варіанту, необхідно набрати, запустити та оформити у звіті наступну програму для вводу, компiляцiї, вiдлагодження та виконання:
#include <stdio.h>
#include <conio.h>
main() {
float a,b;
char opr;
double result;
textbackground(RED);
clrscr();
textcolor(YELLOW);
puts(“Здiйснiть ввiд по формату: операнд1 операцiя операнд2 <Enter>”);
puts(“Для закiнчення роботи натиснiсть клавiшу Esc”);
window(1,4,80,25);
textbackground(BLUE);
clrscr();
while(cputs(“Ввiд->”),cscanf(“%f %c %f”,&a,&opr,&b)!=0) {
switch (opr) {
case ‘+’: result=a+b;break;
case ‘-’: result=a-b;break;
case ‘*’: result=a*b;break;
case ‘/’:if (b==0) { cputs(“\n\rПомилка: дiлення на нуль!!\n\r”); continue; }
else {result=a/b;break;}
default:{ cputs(“\n\rПомилка: недопустимий код операцiї!!\n\r”); continue;} }
gotoxy(20,wherey());
cprintf(“=%f\n\r”,result); }
return 0;}
Результат
На рис.1 ми бачимо результат виконання чотирьох дій.
Рис.1
2. Модифікувати навчальний приклад, поданий у даній роботі так, щоб на екран виводилась інформація про студента.
3. Створити програму, яка виводить на екран інформацію про студента в такому форматі:
#include <stdio.h>
#include <conio.h>
main() {
puts(“Mene zvut Maksym Xorkanin”);
puts(“Meni 17 rokiv”);
puts(“Na osinij sesiyi ya otrymav taki ocinky:”);
puts(“Informatyuka – 4”);
puts(“Mat.analiz – 4”);
puts(“Ukr. mova – 4”);
getch();
return 0; }
Результат
На рис.2 ми бачимо екран на якому виводиться особиста інформація студента.
Рис.2
Другий рівень
Набрати (або скопіювати) наведений у роботі текст програми „SNAKE”.
/*************************************************************/ /* ІГРОВА ПРОГРАМА “SNAKE” */ /*************************************************************/ /*
#include <stdio.h>
#include <conio.h>
#include <math.h>
#include <dos.h>
#include <stdlib.h>
#include <time.h>
#define GameTime 30
#define Speed 900
struct w {char x,y;
struct w *next;
struct w *before; };
void cursor_off(void);
cursor_on(void);
void main(){
int x1=10,y1=9,x2=70,y2=19,x,y,mark=0;
char symbol,c,attrib,h=259,refresh;
struct w *head=NULL,*tail, *p, *q,*r; time_t t1,t2;
time(&t1);
cursor_off();
srand(time(NULL));
textbackground(BLACK);
textcolor(LIGHTGRAY);
clrscr();
textcolor(GREEN);
gotoxy(20,1);cputs(" *** * * ** * * *****");
gotoxy(20,2);cputs("* * ** * * * * * * ");
gotoxy(20,3);cputs(" * * * * * * ** **** ");
gotoxy(20,4);cputs(" * * * * ***** * * * ");
gotoxy(20,5);cputs("* * * ** * * * * * ");
gotoxy(20,6);cputs(" *** * * * * * * *****");
textcolor(LIGHTGRAY);
gotoxy(20,21);cputs("Press arrows key for moving the snake.");
gotoxy(7,22);cputs("If the head gets on a symbol '+' the length of the snake is increased.");
gotoxy(7,23);cputs("If the head gets on a symbol '-' the length of the snake decreases.");
gotoxy(15,24); cputs("Try to construct the greatest length of the snake.");
textbackground(BLUE);
textcolor(WHITE);
x=x1-1; y=y1-1; gotoxy(x,y);putch(201);
y=y1-1;for(x=x1;x<=x2;x++){gotoxy(x,y);putch(205);
x=x2+1; y=y1-1; gotoxy(x,y);putch(187);
x=x2+1; for(y=y1;y<=y2;y++){gotoxy(x,y);putch(186);}
x=x2+1; y=y2+1; gotoxy(x,y);putch(188);
y=y2+1; for(x=x2;x>=x1;x--){gotoxy(x,y);putch(205);}
x=x1-1; y=y2+1; gotoxy(x,y);putch(200);
x=x1-1; for(y=y1;y<=y2;y++){gotoxy(x,y);putch(186);}
window(x1,y1,x2,y2);
clrscr();
for(x=1;x<=x2-x1+1;x++) for(y=1;y<=y2-y1+1;y++)
if(!(y==y2-y1+1&&x==x2-x1+1)) if((float)rand()/RAND_MAX>0.9) putch('+');
else if((float)rand()/RAND_MAX>0.9) putch('-');
else putch(' ');
textcolor(BLACK);
x=wherex();
y=wherey();
attrib=peekb(0xB800,(y1+y-2)*80*2+(x1+x-2)*2+1);
tail=(struct w*) malloc(sizeof(struct w));
tail->x=x;
tail->y=y;
tail->next=head;
head=tail;
pokeb(0xB800,(y1+head->y-2)*80*2+(x1+head->x-2)*2+1,0x30);
pokeb(0xB800,(y1+y-2)*80*2+(x1+x-2)*2, h);
do{
if(kbhit()){ c=getch();if(c==0)c=getch();refresh=1;}
switch(c){
case 72: y--;if(y<1) {y=1; refresh=0;} h=30; break;
case 80: y++;if(y>y2-y1+1) {y=y2-y1+1; refresh=0;} h=31; break;
case 75: x--;if(x<1) {x=1; refresh=0;} h=17; break;
case 77: x++;if(x>x2-x1+1) {x=x2-x1+1; refresh=0;} h=16; break;
default: refresh=0;}
pokeb(0xB800,(y1+head->y-2)*80*2+(x1+head->x-2)*2, h);
if(refresh==1){q=(struct w*) malloc(sizeof(struct w));
q->x=x;
q->y=y;
q->next=head;
q->before=NULL;
head->before=q;
head=q;
symbol=peekb(0xB800,(y1+y-2)*80*2+(x1+x-2)*2); if(symbol=='+')mark++;
pokeb(0xB800,(y1+head->y-2)*80*2+(x1+head->x-2)*2,h);
pokeb(0xB800,(y1+head->y-2)*80*2+(x1+head->x-2)*2+1,0x30);
if(head->next!=NULL) {pokeb(0xB800,(y1+head->next->y-2)*80*2+(x1+head->next->x-2)*2,' ');
pokeb(0xB800,(y1+head->next->y-2)*80*2+(x1+head->next->x-2)*2+1,0x30); }
if(symbol==' ') {r=tail; tail=tail->before; tail->next=NULL;
pokeb(0xB800,(y1+r->y-2)*80*2+(x1+r->x-2)*2+1, attrib); free(r); }
if(symbol=='-') {mark--; r=tail;
if(tail->before!=head) { tail=tail->before->before;
pokeb(0xB800,(y1+r->before->y-2)*80*2+(x1+ r->before->x-2)*2+1, attrib);
free(r->before); }
else if(tail!=head) tail=tail->before;
tail->next=NULL;
pokeb(0xB800,(y1+r->y-2)*80*2+(x1+r->x-2)*2+1,attrib);
free(r);}
gotoxy(x,y);
delay(Speed?abs(1000-Speed):10000); }
time(&t2); }while(c!=27&&(t2-t1<GameTime));
textbackground(BLUE);
textcolor(WHITE);
clrscr()
; gotoxy(25,5);cputs("GAME OVER");
gotoxy(16,6);cprintf("%s %d %s","Your prize makes",mark,"points"); getch();
cursor_on();}
void cursor_off(){_AH=0x1;_CH=0x20;geninterrupt(0x10);}
void cursor_on(){_AH=0x1;_CH=0x6;_CL=0x7;geninterrupt(0x10);}
Результат
На рис.3,4 ми бачимо вікно на якому зображена програма “Змійка”
Рис.3
Рис.4
Третій рівень
А. Наступна програма (файл preproc.c), використовуючи директиви препроцесора, записані на її початку, здійснює введення цілих чисел, обчислює та виводить квадрати їх значень. Вiдкомпiлювати, вiдлагодити та виконати програму.
#include <stdio.h>
#define n 5
#define begin {
#define end }
#define integer int
#define Program void
#define MyPrg main()
#define loop(n) for(i=1;i<=n;i++)
#define read(type,x) scanf(“%”#type,&x)
#define write(type,x) printf(“%”#type,x)
#define writeln(type,x) printf(#x”=%”#type”\n”,x)
#define SQR(x) ((x)*(x))
Program MyPrg
begin
integer i,x;
loop(n)
begin
write(s,”Input integer x of range 1..100->”);
read(d,x);
writeln(d,SQR(x));
end
end
Результат
На рис.5 ми бачимо результат виконня програми.
Рис.5
Б. Написати макрос, який повертає 1, якщо рiвняння 2 0 ax bx c (a<>0, b<>0, c<>0) має два рiзних дiйсних коренi, і 0 - в інших випадках.
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <conio.h>
using namespace std;
#define ABC(a, b, c, d) (d=(b*b)-(4*a*c))>0?1:0;
int main()
{
int a, b, c,d, res;
std::cin >> a>>b>>c;
res=ABC(a, b, c,d );
std::cout << res;
_getch();
return 0;
}
Результат
На рис.6,7 ми бачимо результат розвязування квадратних рівнянь.
Рис.6
Рис.7
Висновок:
Ми ознайомились із середовищем Borland C++ 3.1, вивчили способи запису програми на мові Сі, ознайомились з основними конструкціями мови Сі. Вивчили призначення, правила побудови та застосування засобiв препроцесорного опрацювання текстів програм на мовi Сі.