Задача 1.
Задан типизированный файл целых чисел. На его основе создайте текстовый файл, в каждой строке которого необходимо записать число в десятичной системе счисления из исходного файла и соответствующее ему число в двоичной системе счисления.
Действие программы.
Программа создает/перезаписывает файл output.txt. Затем запускает цикл, где считывает числовое значение из input, делит на 2 до тех пор, пока число не равняется 1 или меньше. При каждом делении – записывает остаток в начало строчной переменной. Результат записывается в файл output.txt. И так с остальными числами.
Назначение переменных
Переменная | Тип | Назначение |
f1 | File of integer | Исходный файл input с числами из десятичной системы числения |
f2 | text | Файл output.txt с числами из двоичной системы числения |
iNumber | integer | Десятичное число из файла input для для получения числа из двоичной системы числения |
sText, sText2 | string | Строчные переменные для получения двоичного числа |
Текст программы.
program lab09_01;
Var
f1: file of integer; // Исходный файл с числами
f2: text; // Файл с обработанными числами
iNumber: Integer;
sText, sText2: string;
cType: char; // Переменная для перезаписи исходного файла
// Процедура для перезаписи исходного файла. Может быть пропущено.
Procedure writeNumbers ();
Var
f: integer;
i: integer;
Begin
writeln('Сколько чисел записать?'); readln(f);
assign(f1,'input');
rewrite(f1);
for i:= 1 to f do begin
write(i, ') ');
readln(iNumber);
write(f1, iNumber);
end;
close(f1);
end;
Begin
write('Хотите перезаписать целые числа в исходный файл? (y или n) '); readln(cType);
if cType = 'y' then writeNumbers();
assign(f1,'input'); assign(f2,'output.txt');
reset(f1); rewrite(f2); { открываем f1 и создаем f2 }
while not eof(f1) do
Begin
read(f1, iNumber); // Узнаем число из десятичной системы числения
write(f2, iNumber:4,' | '); // Выводим число из десятичной системы числения
while iNumber >= 1 do begin
Str(iNumber mod 2, sText2); // Записываем остаток в виде символа
Insert(sText2,sText,1); // Вставляем остаток в начало двоичной системы
iNumber:= iNumber div 2; // Делим число на 2
end;
writeln(f2, sText); // Записываем ответ в файл
sText:= ''; // Обнуляем строчную переменную
Delete(sText, Length(sText), 1)
end;
close(f1); close(f2);
writeln; write('Результат сохранен в output.txt');
writeln; write('Программа закончила свою работу...'); readln;
end.
Тестирование программы
Пример 1
Хотите перезаписать целые числа в исходный файл? (y или n) n
Результат сохранен в output.txt
Программа закончила свою работу...
Содержимое input:
1 5 8 15 35 68 54 127
Содержимое output.txt:
1 | 1
5 | 101
8 | 1000
15 | 1111
35 | 100011
68 | 1000100
54 | 110110
127 | 1111111
Задача 2.
Разработать библиотечный модуль, содержащий следующие подпрограммы (процедуры или функции) для работы со строками:
А. Подсчитать количество букв в последнем слове заданной строки
Б. Заменить в заданной строке все заглавные буквы на строчные.
В. Удалить все знаки препинания.
Написать программу, к которой подключается модуль, демонстрирующую работоспособность всех подпрограмм модуля.
Работа программы
К программе подключается библиотечный модуль. Затем программа использует их функции и процедуры для работы со строками.
Назначение переменных
Переменная | Тип | Назначение |
sName | string | Название файла. Вводится с клавиатуры. |
iLine | integer | Номер строки. Вводится с клавиатуры. |
i | integer | Счетчик цикла |
f1 | text | Файловая переменная файла |
sText | string | Строчная переменная для обработки строки |
x | integer | Счетчик символов (Для выполнения задания - А) |
Текст программы.
program lab09_02;
uses module;
Var
sName:string;
iLine:integer;
Begin
write('Введите название файла: '); readln(sName);
// Задание A
writeln('A.Подсчитать количество букв в последнем слове заданной строки');
write('Введите номер строки '); readln(iLine);
writeln('Ответ: ', subprogramme_A(FindLine(sName, iLine))); writeln;
// Задание B
writeln('Б. Заменить в заданной строке все заглавные буквы на строчные.');
write('Введите номер строки '); readln(iLine);
writeln('Ответ: ', subprogramme_B(FindLine(sName, iLine))); writeln;
// Задание C
writeln('C. Удалить все знаки препинания.');
subprogramme_C(sName);
end.
Текст библиотечного модуля.
unit module;
Interface
function FindLine(sName:string; iLine:integer):string;
function ValidPunctuationMark(cText:char):boolean;
function subprogramme_A(sText:string):integer;
function subprogramme_B(sText:string):string;
procedure subprogramme_C(sName:string);
Implementation
function FindLine:string;
Var
i:integer;//Счетчик цикла и символов.
f1:text;
sText:string;
Begin
assign(f1, sName);reset(f1);
for i:=1 to iLine-1 do
Begin
readln(f1);
end;
readln(f1,sText);
close(f1);
FindLine:= sText;
end;
function ValidPunctuationMark:boolean;
Begin
case cText of
'.': ValidPunctuationMark:= true;
',': ValidPunctuationMark:= true;
':': ValidPunctuationMark:= true;
';': ValidPunctuationMark:= true;
'?': ValidPunctuationMark:= true;
'!': ValidPunctuationMark:= true;
else ValidPunctuationMark:= false;
end;
end;
function subprogramme_A:integer;
Var
i,x:integer;//Счетчик цикла и символов.
Begin
writeln('Текст: ', sText);
for i:=Length(sText) downto 1 do
Begin
if ((sText[i] = ' ') or (ValidPunctuationMark(sText[i]))) and (x = 0) then continue
else if ((sText[i] = ' ') or (ValidPunctuationMark(sText[i]))) then break;
Inc(x);
End;
subprogramme_A:=x;
end;
function subprogramme_B:string;
Var
i:integer;//Счетчик цикла.
Begin
writeln('Текст: ', sText);
for i:=1 to length(sText) do
sText[i]:= LowCase(sText[i]);
subprogramme_B:= sText;
end;
procedure subprogramme_C;
Var
i:integer;//Счетчик цикла.
f1:text;
sText:string;
Begin
assign(f1,sName);reset(f1);
while not eof(f1) do
Begin
readln(f1, sText);
for i:=length(sText) downto 1 do
if ValidPunctuationMark(sText[i]) then delete(sText,i,1);
writeln(sText);
end;
close(f1);
end;
Begin
end.
Тестирование программы
Введите название файла: text.txt
A.Подсчитать количество букв в последнем слове заданной строки
Введите номер строки 2
Текст: Computers that once weighed 30 tons now may weigh as little as 1.8 kilograms. Microchips and microprocessors have...
Ответ: 4
Б. Заменить в заданной строке все заглавные буквы на строчные.
Введите номер строки 3
Текст: Until the late 1970s, the computer was viewed as a massive machine that was useful to big business and big government but not to the general public.
Ответ: until the late 1970s, the computer was viewed as a massive machine that was useful to big business and big government but not to the general public.
C. Удалить все знаки препинания.
Generally any device that can perform numerical calculations even an adding machine may be called a computer but nowadays this term is used especially for digital computers
Computers that once weighed 30 tons now may weigh as little as 18 kilograms Microchips and microprocessors have
Until the late 1970s the computer was viewed as a massive machine that was useful to big business and big government but not to the general public
Computers were too cumbersome and expensive for private use and most people were intimidated by them
As technology advanced this was changed by a distinctive group of engineers and entrepreneurs
Содержимое файла text.txt
Generally, any device that can perform numerical calculations, even an adding machine, may be called a computer but nowadays this term is used especially for digital computers.
Computers that once weighed 30 tons now may weigh as little as 1.8 kilograms. Microchips and microprocessors have...
Until the late 1970s, the computer was viewed as a massive machine that was useful to big business and big government but not to the general public.
Computers were too cumbersome and expensive for private use, and most people were intimidated by them.
As technology advanced, this was changed by a distinctive group of engineers and entrepreneurs...