|
Вопрос # 1 535/ вопрос открыт / |
|
Здравствуйте, уважаемые эксперты!
Снова я обращаюсь к Вам за помощью... написала программку - она работает, но код очень громадный и мне кажется нерациональный. Можно ли как-то эту задачу сократить, чтобы код был не такой огромный? Вот условие задачи:
C помощью подпрограммы поменять местами первый и последний столбцы матриц A(12,9), C(7,11), и третий и пятый столбц матрицы B(8,15). Исходные и преобразованные матрицы вывести на экран дисплея. Элементы входных матриц вычисляются по формулам:
A(c индексом i,j)=tg(j)+e^cos(i);
B(c индексом i,j)=sin(3.2j+4.2)+e^tg(1.5i);
C(c индексом i,j)=cos(12.4j+1).
Данные стрингридов чтобы можно было схранять в файл и выводить из из него.
Вот мой огромный код. Спасибо!
Приложение: Переключить в обычный режим- unit Unit6;
-
- interface
-
- uses
- Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
- Dialogs, StdCtrls, Grids, Math, Buttons;
-
- type
- TForm6 = class(TForm)
- Button1: TButton;
- StringGrid1: TStringGrid;
- Button6: TButton;
- Button10: TButton;
- Label9: TLabel;
- Label10: TLabel;
- StringGrid2: TStringGrid;
- StringGrid3: TStringGrid;
- StringGrid4: TStringGrid;
- StringGrid5: TStringGrid;
- StringGrid6: TStringGrid;
- Label1: TLabel;
- Label2: TLabel;
- Label3: TLabel;
- Label4: TLabel;
- Label5: TLabel;
- Label6: TLabel;
- BitBtn1: TBitBtn;
- BitBtn2: TBitBtn;
- BitBtn3: TBitBtn;
- BitBtn4: TBitBtn;
-
- procedure Button1Click(Sender: TObject);
- procedure Button6Click(Sender: TObject);
-
-
-
- procedure Button10Click(Sender: TObject);
- procedure BitBtn1Click(Sender: TObject);
- procedure BitBtn2Click(Sender: TObject);
- procedure BitBtn3Click(Sender: TObject);
- procedure BitBtn4Click(Sender: TObject);
-
-
-
- private
- { Private declarations }
- public
- { Public declarations }
- end;
-
- var
- Form6: TForm6;
- Y:array of array of real;
- C:array of array of real;
- A:array of array of real;
- B:array of array of real;
- n:integer;
- m:integer;
- k:integer;
- l:integer;
-
- implementation
-
- uses Unit1;
-
- {$R *.dfm}
-
- procedure TForm6.Button1Click(Sender: TObject);
- begin
- Form1.Show;
- Form6.Close;
- end;
-
- procedure TForm6.Button6Click(Sender: TObject);
- var i,j,t:integer;
- tmp:real;
- begin
- begin
- n:=7;
- m:=11;
- setlength(C,n,m);
- stringgrid3.RowCount:=n;
- stringgrid3.ColCount:=m;
- for i:=0 to n-1 do
- for j:=0 to m-1 do
- begin
- C[i,j]:=cos(14*j+1);
- stringgrid3.Cells[j,i]:=FormatFloat('0.00',C[i,j]);
- end;
- end;
- begin
- m:=stringgrid3.ColCount;
- k:=0;
- l:=10;
- for i:=0 to n-1 do
- begin
- tmp:=C[i,k];
- C[i,k]:=C[i,l];
- C[i,l]:=tmp;
- end;
- for t:=0 to n-1 do
- for j:=0 to m-1 do
- stringgrid6.Cells[j,t]:=FormatFloat('0.00',C[t,j]);
- end;
- begin
- n:=8;
- m:=15;
- setlength(B,n,m);
- stringgrid2.RowCount:=n;
- stringgrid2.ColCount:=m;
- for i:=0 to n-1 do
- for j:=0 to m-1 do
- begin
- B[i,j]:=sin(3.2*j+4.2)+power(exp(1),tan(i));
- stringgrid2.Cells[j,i]:=FormatFloat('0.00',B[i,j]);
- end;
- end;
- begin
- m:=stringgrid2.ColCount;
- k:=2;
- l:=4;
- for i:=0 to n-1 do
- begin
- tmp:=B[i,k];
- B[i,k]:=B[i,l];
- B[i,l]:=tmp;
- end;
- for t:=0 to n-1 do
- for j:=0 to m-1 do
- stringgrid5.Cells[j,t]:=FormatFloat('0.00',B[t,j]);
- end;
- begin
- n:=12;
- m:=9;
- setlength(A,n,m);
- stringgrid1.RowCount:=n;
- stringgrid1.ColCount:=m;
- for i:=0 to n-1 do
- for j:=0 to m-1 do
- begin
- A[i,j]:=sin(j)/cos(j)+exp(cos(i));;
- stringgrid1.Cells[j,i]:=FormatFloat('0.00',A[i,j]);
- end;
- end;
- begin
- m:=stringgrid1.ColCount;
- k:=0;
- l:=8;
- for i:=0 to n-1 do
- begin
- tmp:=A[i,k];
- A[i,k]:=A[i,l];
- A[i,l]:=tmp;
- end;
- for t:=0 to n-1 do
- for j:=0 to m-1 do
- stringgrid4.Cells[j,t]:=FormatFloat('0.00',A[t,j]);
- end;
- end;
- procedure TForm6.Button10Click(Sender: TObject);
- var
- i,j:integer;
- begin
- begin
- for i:=0 to StringGrid6.ColCount-1 do
- for j:=0 to StringGrid6.RowCount-1 do
- StringGrid6.Cells[i,j]:='';
- end;
- begin
- for i:=0 to StringGrid5.ColCount-1 do
- for j:=0 to StringGrid5.RowCount-1 do
- StringGrid5.Cells[i,j]:='';
- end;
- begin
- for i:=0 to StringGrid4.ColCount-1 do
- for j:=0 to StringGrid4.RowCount-1 do
- StringGrid4.Cells[i,j]:='';
- end;
- begin
- for i:=0 to StringGrid3.ColCount-1 do
- for j:=0 to StringGrid3.RowCount-1 do
- StringGrid3.Cells[i,j]:='';
- end;
- begin
- for i:=0 to StringGrid2.ColCount-1 do
- for j:=0 to StringGrid2.RowCount-1 do
- StringGrid2.Cells[i,j]:='';
- end;
- begin
- for i:=0 to StringGrid1.ColCount-1 do
- for j:=0 to StringGrid1.RowCount-1 do
- StringGrid1.Cells[i,j]:='';
- end;
- end;
-
- procedure TForm6.BitBtn1Click(Sender: TObject);
- var
- s :TStringlist;
- j:Integer;
- Str:String;
- posy, posx, i : Integer;
-
- Begin
- with TSaveDialog.Create(Owner) do
- begin
- DefaultExt:='.txt';
-
- if not Execute then exit;
- s:=TStringList.Create;
- s.Clear;
- for i:=0 to StringGrid1.RowCount-1 do
- begin
- Str := '';
- for j:=0 to StringGrid1.ColCount-1 do
- str:=str+StringGrid1.Cells[j, i]+' ';
- s.Add(Str);
- end;
- s.Add('T2');
- for i:=0 to StringGrid2.RowCount-1 do
- begin
- Str := '';
- for j:=0 to StringGrid2.ColCount-1 do
- str:=str+StringGrid2.Cells[j, i]+' ';
- s.Add(Str);
- end;
- s.Add('T3');
- for i:=0 to StringGrid3.RowCount-1 do
- begin
- Str := '';
- for j:=0 to StringGrid3.ColCount-1 do
- str:=str+StringGrid3.Cells[j, i]+' ';
- s.Add(Str);
- end;
-
- S.SaveToFile(FileName);
- end;
- s.Free;
- end;
-
- procedure TForm6.BitBtn2Click(Sender: TObject);
- var
- s :TStringlist;
- i,j,yd:Integer;
- Str:String;
- posy, posx, py: Integer;
- t1,t2,t3:boolean;
-
-
- Begin
- t1:=true;
- t2:=false;
- t3:=false;
- with TOpenDialog.Create(Owner) do
- begin
- py:=0;
- DefaultExt:='.txt';
-
- if not Execute then exit;
- s:=TStringList.Create;
- S.LoadFromFile(FileName);
- For posy := 1 to S.Count do
- begin
- posx := 0;
- Str := '';
- For i := 1 to Length(S.Strings[posy-1]) do
- begin
- if S.Strings[posy-1][i] <> ' ' then
- begin
- Str := Str + S.Strings[posy-1][i];
- if Str = 'T2' then
- begin
- t1:=false;
- t2:=true;
- py:=posy;
- end;
- if Str = 'T3' then
- begin
- t1:=false;
- t2:=false;
- t3:=true;
- py:=posy;
- end;
- end
- else
- begin
- if t1= true then StringGrid1.Cells[posx, posy-1] := Str;
- if t2 = true then StringGrid2.Cells[posx, posy-1-py] := Str;
- if t3 = true then StringGrid3.Cells[posx, posy-1-py] := Str;
- Str := '';
- inc(posx);
- end;
- end;
- end;
- end;
- S.Free;
- end;
-
- procedure TForm6.BitBtn3Click(Sender: TObject);
- var
- s :TStringlist;
- j:Integer;
- Str:String;
- posy, posx, i : Integer;
-
- Begin
- with TSaveDialog.Create(Owner) do
- begin
- DefaultExt:='.txt';
-
- if not Execute then exit;
- s:=TStringList.Create;
- s.Clear;
- for i:=0 to StringGrid4.RowCount-1 do
- begin
- Str := '';
- for j:=0 to StringGrid4.ColCount-1 do
- str:=str+StringGrid4.Cells[j, i]+' ';
- s.Add(Str);
- end;
- s.Add('T2');
- for i:=0 to StringGrid5.RowCount-1 do
- begin
- Str := '';
- for j:=0 to StringGrid5.ColCount-1 do
- str:=str+StringGrid5.Cells[j, i]+' ';
- s.Add(Str);
- end;
- s.Add('T3');
- for i:=0 to StringGrid6.RowCount-1 do
- begin
- Str := '';
- for j:=0 to StringGrid6.ColCount-1 do
- str:=str+StringGrid6.Cells[j, i]+' ';
- s.Add(Str);
- end;
-
- S.SaveToFile(FileName);
- end;
- s.Free;
- end;
-
-
- procedure TForm6.BitBtn4Click(Sender: TObject);
- var
- s :TStringlist;
- i,j,yd:Integer;
- Str:String;
- posy, posx, py: Integer;
- t1,t2,t3:boolean;
-
-
- Begin
- t1:=true;
- t2:=false;
- t3:=false;
- with TOpenDialog.Create(Owner) do
- begin
- py:=0;
- DefaultExt:='.txt';
-
- if not Execute then exit;
- s:=TStringList.Create;
- S.LoadFromFile(FileName);
- For posy := 1 to S.Count do
- begin
- posx := 0;
- Str := '';
- For i := 1 to Length(S.Strings[posy-1]) do
- begin
- if S.Strings[posy-1][i] <> ' ' then
- begin
- Str := Str + S.Strings[posy-1][i];
- if Str = 'T2' then
- begin
- t1:=false;
- t2:=true;
- py:=posy;
- end;
- if Str = 'T3' then
- begin
- t1:=false;
- t2:=false;
- t3:=true;
- py:=posy;
- end;
- end
- else
- begin
- if t1= true then StringGrid4.Cells[posx, posy-1] := Str;
- if t2 = true then StringGrid5.Cells[posx, posy-1-py] := Str;
- if t3 = true then StringGrid6.Cells[posx, posy-1-py] := Str;
- Str := '';
- inc(posx);
- end;
- end;
- end;
- end;
- S.Free;
- end;
-
- end.
-
 |
Вопрос задала: Violina (статус: Посетитель)
Вопрос отправлен: 28 апреля 2008, 14:45
Состояние вопроса: открыт, ответов: 1.
|
Ответ #1. Отвечает эксперт: min@y™
Разбираться в чужом коде сложнее и дольше, чем написать программу с нуля. Особенно, когда в этом коде нету ни единого комментария!
Мне пока заняться нечем, поэтому я написал свой проект и прицепляю его к ответу.
Как говорится - "найди 10 отличий".
З.Ы. Сохранение/загрузку не писал, т.к. из условия непонятно, в каком формате (текстовый или двоичный) хранить данные. Если скажешь - могу дописать. К ответу прикреплён файл. Загрузить » (срок хранения: 60 дней с момента отправки ответа)
 |
Ответ отправил: min@y™ (статус: Доктор наук)
Время отправки: 29 апреля 2008, 09:27
Оценка за ответ: 5
Комментарий к оценке: спасибо огромное
|
Мини-форум вопроса
Всего сообщений: 8; последнее сообщение — 30 апреля 2008, 08:21; участников в обсуждении: 3.
|
Violina (статус: Посетитель), 29 апреля 2008, 11:58 [#1]:
min@y™ спасибо Вам огромное за программу! Мне надо чтобы на одну кнопку можно было сохранить в текстовый файл, а на другую из него в стринггриды вывести.. чтобы сами дирректорию файла сохранения указывали.. и сделайте, пожалуйста, кнопку очистки - ато у меня очистка получаетя на 1000 символов... ну и то что для меня совсем сложно - блок-схема.. просто в Вашей программе для меня очень много нового и непонятного..
|
|
Косолапов Дмитрий Юрьевич (статус: 8-ой класс), 29 апреля 2008, 11:59 [#2]:
Вообще, конечно, конструкции типа if t1=true очень "радуют" - раз t1 булевская переменная, то ее незачем сравнивать с true
|
|
min@y™ (статус: Доктор наук), 29 апреля 2008, 14:06 [#3]:
Раз файл должен быть текстовый (такое условие задачи? ), пришли мне пример его вида. А то что-нибудь не то сделаю. Бинарный файл - проще: текстовый файл придётся парсить при загрузке данных из него.
Цитата:
в Вашей программе для меня очень много нового и непонятного..
Чего там непонятного? Спрашивай.
Делаю лабы и курсачи по Delphi и Turbo Pascal. За ПИВО! Пишите в личку, а лучше в аську. А ещё лучше - звоните в скайп!
|
|
min@y™ (статус: Доктор наук), 29 апреля 2008, 14:39 [#4]:
От тотального безделья на работе дополнил свой пример очисткой, сохранением и загрузкой исходных данных в ini-файл/из ini-файла.
Куды выслать?
Делаю лабы и курсачи по Delphi и Turbo Pascal. За ПИВО! Пишите в личку, а лучше в аську. А ещё лучше - звоните в скайп!
|
|
Violina (статус: Посетитель), 29 апреля 2008, 15:27 [#5]:
Спасибо большое! мне нужно то бы запрашивало куда сохраняло и запрашивало от куда доставать... и ещё...не понятно для чего нужен XPManifest на форме? E-mail Violinka2008@yandex.ru
|
|
min@y™ (статус: Доктор наук), 29 апреля 2008, 16:07 [#6]:
Цитата:
мне нужно то бы запрашивало куда сохраняло и запрашивало от куда доставать
Сделано с помощью TOpenDialog и TSaveDialog.
Цитата:
и ещё...не понятно для чего нужен XPManifest на форме?
Для придания интерфейсу вида под текущую тему Windows XP. Попробуй его удалить и пересобрать. Увидишь, что получится.
Исходник выслал по указанному адресу.
Делаю лабы и курсачи по Delphi и Turbo Pascal. За ПИВО! Пишите в личку, а лучше в аську. А ещё лучше - звоните в скайп!
|
|
Violina (статус: Посетитель), 29 апреля 2008, 16:30 [#7]:
спасиб) за всё... но письма я не получила...
|
|
min@y™ (статус: Доктор наук), 30 апреля 2008, 08:21 [#8]:
Странно, однако, может твой сервер отсеял моё письмо как спам, такое бывает. Ладно, закачал я файл на сервис для скачивания. Чтоб скачать, тыкай сюда.
Делаю лабы и курсачи по Delphi и Turbo Pascal. За ПИВО! Пишите в личку, а лучше в аську. А ещё лучше - звоните в скайп!
|
Чтобы оставлять сообщения в мини-форумах, Вы должны авторизироваться на сайте.
|