Форум программистов, компьютерный форум, киберфорум
C/C++: WinAPI
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/3: Рейтинг темы: голосов - 3, средняя оценка - 4.67
3 / 3 / 2
Регистрация: 24.03.2020
Сообщений: 153

Тестирование класса на C++

29.11.2020, 16:21. Показов 651. Ответов 1

Студворк — интернет-сервис помощи студентам
Друзья, привет.
Прошу помочь с приложением. В общем нужно реализовать тестирование класса как в приведённом ниже коде "Тестирование классов.cpp", только по кнопке и когда прогресс бар заполнился на 100, выводилось сообщение с надписью "Тестирование класса Quadratic, OK", а если в нём что-то поломать, то так "Тестирование класса Quadratic завершилось с ошибкой", вот как то так. Это мне нужно реализовать в коде Form1.h, наставьте на путь истинный, я не представляю даже как это осуществить. Все коды ниже. Программа "Калькулятор квадратных уравнений". Спасибо.

Тестирование классов.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
//Тестирование класса обработки комплексных чисел
//Тестирование класса обработки комплексных чисел
#include "stdafx.h"
#include <iostream>
 
using namespace System;
using namespace std;
 
class Complex{
private: 
    double re, im;
public: 
    Complex():re(0.0),im(0.0){};
    Complex(double pRe, double pIm=0.0){re=pRe; im=pIm;};
    double GetRe(){return re;};
    double GetIm(){return im;};
    //унарные операторы
    Complex operator-(){return Complex(-re,-im);};
    Complex operator+(){return Complex(re, im);};
    Complex operator*=(const Complex &c) 
    {   double newRe = re*c.re - im*c.im;
        double newIm = im*c.re + re*c.im;
        re = newRe; im=newIm; return *this;};
    Complex operator+=(const Complex &c){re+=c.re; im+=c.im; return *this;}; 
    Complex operator-=(const Complex &c){re-=c.re; im-=c.im; return *this;};
    Complex operator/=(const Complex &c)
    {   double d = c.re*c.re + c.im*c.im;
        double newRe = (re*c.re + im*c.im)/d;
        double newIm = (im*c.re - re*c.im)/d;
        re = newRe; im = newIm; return *this;};
    //бинарные операции
    friend const Complex operator+(const Complex& left, const Complex& right) {return Complex(left.re + right.re, left.im + right.im);};
    friend const Complex operator-(const Complex& left, const Complex& right){return Complex(left.re - right.re, left.im - right.im);};
    friend const Complex operator*(const Complex& left, const Complex& right) 
    {return Complex(left.re * right.re - left.im * right.im, left.im * right.re + left.re * right.im );}
    friend const Complex operator/(const Complex& left, const Complex& right)
    {return Complex((left.re * right.re + left.im * right.im)/right.re*right.re+right.im*right.im,
    (left.im * right.re - left.re * right.im)/right.re*right.re+right.im*right.im);};
    friend const bool operator==(const Complex& left, const Complex& right)
    {return left.re == right.re && left.im == right.im;};
    bool operator!=(Complex p2){return this->re!=p2.re || this->im != p2.im;};
    friend ostream& operator<<(ostream& o,Complex& pComplex);
};
 
void TestClassComplexConstructor(){
    Complex c;
    if(c.GetRe()!=0.0 || c.GetIm()!=0.0)throw "TestClassComplexConstructor()";
}
 
void TestClassComplexConstructor1(){
    double a = 1.0/5.0;
    Complex c = a;
    if(c.GetRe()!=a) throw "TestClassComplexConstructor1 GetRe()";
    if(c.GetIm()!=0.0) throw "TestClassComplexConstructor1 GetIm()";
}
void TestClassComplexConstructor2(){
    double a = 1.0/5.0, b = 2.0/7.0;
    Complex c (a,b);
    if(c.GetRe()!=a) throw "TestClassComplexConstructor2 GetRe()";
    if(c.GetIm()!=b) throw "TestClassComplexConstructor2 GetIm()";
}
 
bool DoubleEquals(const double left, const double right){
    const double EPSILON = 1e-06;
    return abs(left - right)<=EPSILON;
}
 
void TestClassComplexConstructorUnPl(){
    double a=2.0/4.0, b=5.0/6.0;
    Complex c1(a,b);
    Complex c2 = +c1;
    if(c2.GetRe() != c1.GetRe() || c2.GetIm() != c1.GetIm()) throw "TestClassComplexUnPl() +";
    if (c1.GetRe() !=a || c1.GetIm() != b) throw "TestClassComplexUnPl() changed c1";
}
 
void TestClassComplexConstructorUnMin(){
    double a=8.0/6.0, b=7.0/4.0;
    Complex c1(a,b);
    Complex c2 = -c1;
    if(c2.GetRe() != -c1.GetRe() || c2.GetIm() != -c1.GetIm()) throw "TestClassComplexUnMin() -";
    if (c1.GetRe() !=a || c1.GetIm() != b) throw "TestClassComplexUnMin() changed c1";
}
 
void TestClassComplexConstructorUnPlRav(){
    //(5.2+10.4i)+(8.2+10.4i)=13.4+20.8i
    Complex c1 (5.2,10.4);
    double a=8.2, b=10.4;
    Complex c2 (a,b);
    c1 += c2;
    //Complex c2 = +c1;
    if( !DoubleEquals(c1.GetRe(),13.4) || !DoubleEquals(c1.GetIm(),20.8)) 
        throw "TestClassComplexUnPlRav() +=";
    if (c2.GetRe() !=a || c2.GetIm() != b) 
        throw "TestClassComplexUnPl() changed r-value";
}
 
void TestClassComplexConstructorUnMinRav(){
    //(10.2+12.2i)-(4.1+10.4i)=6.1+1.8i
    Complex c1 (10.2,12.2);
    double a=4.1, b=10.4;
    Complex c2 (a,b);
    c1 -= c2;
    if( !DoubleEquals(c1.GetRe(),6.1) || !DoubleEquals(c1.GetIm(),1.8)) 
        throw "TestClassComplexConstructorUnMinRav() -=";
    if (c2.GetRe() !=a || c2.GetIm() != b) 
        throw "TestClassComplexConstructorUnMinRav() changed r-value";
}
 
void TestClassComplexConstructorUnUmn(){
    Complex c1(1.0, 3.0);
    double c = 5.0, d = -2.0;
    Complex c2(c,d);
    c1*=c2;
    if (!DoubleEquals(c1.GetRe(),11) || !DoubleEquals(c1.GetIm(),13))
        throw "TestClassComplexUnUmn()";
    if (c2.GetRe() !=c || c2.GetIm() !=d)
        throw "TestClassComplexUnUmn() changed c2";
}
 
void TestClassComplexConstructorUnDel(){
    Complex c1(5.0, 10.0);
    double c = 6.0, d = 8.0;
    Complex c2(c,d);
    c1/=c2;
    if (!DoubleEquals(c1.GetRe(), 1.1) || !DoubleEquals(c1.GetIm(),0.2))
        throw "TestClassComplexUnDel()";
    if (c2.GetRe() !=c || c2.GetIm() !=d)
        throw "TestClassComplexUnDel() changed c2";
}
 
void TestClassComplexConstructorBinarPl(){
    double a=1.0/2.0, b=1.0/7.0;
    Complex c1(a,b);
    double c = 2.0/9.0, d=3.0/11.0;
    Complex c2(c,d);
    Complex c3 = c1+c2;
    if (c3.GetRe() !=(a+c) || c3.GetIm() !=(b+d)) throw "TestClassComplexBinarPl() +";
    if (c1.GetRe()!=a || c1.GetIm()!=b) throw "TestClassComplexBinarPl() changed c1";
    if (c2.GetRe()!=c || c2.GetIm()!=d) throw "TestClassComplexBinarPl() changed c2";
}
 
void TestClassComplexConstructorBinarDel(){
    double a=12.0/6.0, b=8.0/9.0;
    Complex c1(a,b);
    double c = 4.0/3.0, d=2.0/3.0;
    Complex c2(c,d);
    Complex c3 = c1/c2;
    if (!DoubleEquals(c3.GetRe(),3.703703704) || !DoubleEquals(c3.GetIm(),0.296296296)) throw "TestClassComplexBinarDel() *";
    if (c1.GetRe()!=a || c1.GetIm()!=b) throw "TestClassComplexBinarDel() changed c1";
    if (c2.GetRe()!=c || c2.GetIm()!=d) throw "TestClassComplexBinarDel() changed c2";
}
 
void TestClassComplexConstructorBinarMin(){
    double a=6.0/3.0, b=8.0/9.0;
    Complex c1(a,b);
    double c = 4.0/2.0, d=4.0/5.0;
    Complex c2(c,d);
    Complex c3 = c1-c2;
    if (c3.GetRe() !=(a-c) || c3.GetIm() !=(b-d)) throw "TestClassComplexBinarMin() -";
    if (c1.GetRe()!=a || c1.GetIm()!=b) throw "TestClassComplexBinarMin() changed c1";
    if (c2.GetRe()!=c || c2.GetIm()!=d) throw "TestClassComplexBinarMin() changed c2";
}
 
void TestClassComplexConstructorBinarYmn(){
    double a=4.0/2.0, b=6.0/1.0;
    Complex c1(a,b);
    double c = 6.0/2.0, d=1.0/8.0;
    Complex c2(c,d);
    Complex c3 = c1*c2;
    if (!DoubleEquals(c3.GetRe(),5.25) || !DoubleEquals(c3.GetIm(),18.25)) throw "TestClassComplexBinarYmn() *";
    if (c1.GetRe()!=a || c1.GetIm()!=b) throw "TestClassComplexBinarYmn() changed c1";
    if (c2.GetRe()!=c || c2.GetIm()!=d) throw "TestClassComplexBinarYmn() changed c2";
}
 
void TestClassComplexConstructorEquals(){
    double a = 5.0/4.0;
    double b = 7.0/4.0;
    Complex c1(a,b);
    Complex c2(a,b);
    if (!(c1==c2)) throw "TestClassComplexOperatorRavnoRavno() ==";
    Complex c3(a,a);
 
    Complex c4(b,b);
}
 
void TestClassComplexConstructorNeRavno(){
    double a = 5.0/3.0; 
    double b = 7.0/3.0;
    Complex c1(a);
    Complex c2(b);
    if (c1==c2) throw "TestClassComplexOperatorRavnoRavno() !=";
}
 
void TestClassComplex(void){
    cout<< "TestClassComplex(void)\n" <<endl;
    TestClassComplexConstructor();
    TestClassComplexConstructor1();
    TestClassComplexConstructor2();
 
    TestClassComplexConstructorUnPl();
    TestClassComplexConstructorUnMin();
    TestClassComplexConstructorUnPlRav();
    TestClassComplexConstructorUnMinRav();
    TestClassComplexConstructorUnUmn();
    TestClassComplexConstructorUnDel();
 
    TestClassComplexConstructorBinarPl();
    TestClassComplexConstructorBinarMin();
    TestClassComplexConstructorBinarYmn();
    TestClassComplexConstructorBinarDel();
    TestClassComplexConstructorEquals();
    TestClassComplexConstructorNeRavno();
} 
int main(array<System::String ^> ^args)
{
    setlocale(LC_CTYPE, "Russian");
 
    try{
        TestClassComplex();
        cout<< "\nTestClassComplex Ok" <<endl;
    }
    catch (const char* mess) {
        cout<< "Тест class Complex завершился с ошибкой "<< mess <<endl;
    }
    catch(...){
        cout<< "Тест TestClassComplex завершился с неизвестной ошибкой" <<endl;
    }
    system("pause");
    return 0;
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
29.11.2020, 16:21
Ответы с готовыми решениями:

Тестирование класса
Добрый вечер. Создал класс для работы со строкам. Нужно его протестировать. В теории понимаю, что самый идеальный тест - это программа,...

Тестирование класса
На этом форуме можно протестировать свой класс? Написал класс для умного указателя, но в нем могут быть какие-нибудь недочеты или ошибки. Я...

Определение и тестирование класса
Доброго времени суток ! Ребят ,только учусь так что не судите строго)) Учусь по книге &quot;Харви М.Дейтел и Пол.Дж.Дейтел - Как...

1
3 / 3 / 2
Регистрация: 24.03.2020
Сообщений: 153
29.11.2020, 16:22  [ТС]
Остальные коды.

Form1.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#pragma once
#include "Quadratic.h"
#include <complex>
 
namespace РешениеКвадратногоУравнения {
 
    using namespace System;
    using namespace System::ComponentModel;
    using namespace System::Collections;
    using namespace System::Windows::Forms;
    using namespace System::Data;
    using namespace System::Drawing;
    using namespace Quadratics;
 
/// <summary>
    /// Сводка для Form1
    /// </summary>
    public ref class Form1 : public System::Windows::Forms::Form
    {
    public:
        Form1(void)
        {
            InitializeComponent();
            //
            //TODO: добавьте код конструктора
            //
        }
 
    protected:
        /// <summary>
        /// Освободить все используемые ресурсы.
        /// </summary>
        ~Form1()
        {
            if (components)
            {
                delete components;
            }
        }
    private: System::Windows::Forms::TextBox^  textBoxA;
    private: System::Windows::Forms::TextBox^  textBoxB;
    private: System::Windows::Forms::TextBox^  textBoxC;
    private: System::Windows::Forms::TextBox^  textBoxX1;
    private: System::Windows::Forms::TextBox^  textBoxX2;
    private: System::Windows::Forms::Button^  buttonCalc;
    private: System::Windows::Forms::Label^  labelA;
    private: System::Windows::Forms::Label^  labelB;
    private: System::Windows::Forms::Label^  labelC;
    private: System::Windows::Forms::Label^  labelX1;
    private: System::Windows::Forms::Label^  labelX2;
    private: System::Windows::Forms::Label^  labelStatus;
    private: System::Windows::Forms::Button^  TestQ1;
 
    private: System::Windows::Forms::ProgressBar^  progressBar1;
    private: System::Windows::Forms::Label^  Test;
 
    protected: 
 
    private:
        /// <summary>
        /// Требуется переменная конструктора.
        /// </summary>
        System::ComponentModel::Container ^components;
 
#pragma region Windows Form Designer generated code
 
        void InitializeComponent(void)
        {
            this->textBoxA = (gcnew System::Windows::Forms::TextBox());
            this->textBoxB = (gcnew System::Windows::Forms::TextBox());
            this->textBoxC = (gcnew System::Windows::Forms::TextBox());
            this->textBoxX1 = (gcnew System::Windows::Forms::TextBox());
            this->textBoxX2 = (gcnew System::Windows::Forms::TextBox());
            this->buttonCalc = (gcnew System::Windows::Forms::Button());
            this->labelA = (gcnew System::Windows::Forms::Label());
            this->labelB = (gcnew System::Windows::Forms::Label());
            this->labelC = (gcnew System::Windows::Forms::Label());
            this->labelX1 = (gcnew System::Windows::Forms::Label());
            this->labelX2 = (gcnew System::Windows::Forms::Label());
            this->labelStatus = (gcnew System::Windows::Forms::Label());
            this->TestQ1 = (gcnew System::Windows::Forms::Button());
            this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar());
            this->Test = (gcnew System::Windows::Forms::Label());
            this->SuspendLayout();
            // 
            // textBoxA
            // 
            this->textBoxA->Font = (gcnew System::Drawing::Font(L"Verdana", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->textBoxA->Location = System::Drawing::Point(71, 12);
            this->textBoxA->Name = L"textBoxA";
            this->textBoxA->Size = System::Drawing::Size(155, 31);
            this->textBoxA->TabIndex = 0;
            this->textBoxA->TextChanged += gcnew System::EventHandler(this, &Form1::textBox_TextChanged);
            this->textBoxA->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form1::textBox_KeyPress);
            // 
            // textBoxB
            // 
            this->textBoxB->Font = (gcnew System::Drawing::Font(L"Verdana", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->textBoxB->Location = System::Drawing::Point(71, 83);
            this->textBoxB->Name = L"textBoxB";
            this->textBoxB->Size = System::Drawing::Size(155, 31);
            this->textBoxB->TabIndex = 0;
            this->textBoxB->TextChanged += gcnew System::EventHandler(this, &Form1::textBox_TextChanged);
            this->textBoxB->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form1::textBox_KeyPress);
            // 
            // textBoxC
            // 
            this->textBoxC->Font = (gcnew System::Drawing::Font(L"Verdana", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->textBoxC->Location = System::Drawing::Point(71, 153);
            this->textBoxC->Name = L"textBoxC";
            this->textBoxC->Size = System::Drawing::Size(155, 31);
            this->textBoxC->TabIndex = 0;
            this->textBoxC->TextChanged += gcnew System::EventHandler(this, &Form1::textBox_TextChanged);
            this->textBoxC->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form1::textBox_KeyPress);
            // 
            // textBoxX1
            // 
            this->textBoxX1->Font = (gcnew System::Drawing::Font(L"Verdana", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->textBoxX1->Location = System::Drawing::Point(343, 12);
            this->textBoxX1->Name = L"textBoxX1";
            this->textBoxX1->Size = System::Drawing::Size(385, 31);
            this->textBoxX1->TabIndex = 0;
            this->textBoxX1->TextChanged += gcnew System::EventHandler(this, &Form1::textBoxX1X2_TextChanged);
            this->textBoxX1->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form1::textBoxX1X2_KeyPress);
            // 
            // textBoxX2
            // 
            this->textBoxX2->Font = (gcnew System::Drawing::Font(L"Verdana", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->textBoxX2->Location = System::Drawing::Point(343, 78);
            this->textBoxX2->Name = L"textBoxX2";
            this->textBoxX2->Size = System::Drawing::Size(385, 31);
            this->textBoxX2->TabIndex = 0;
            this->textBoxX2->TextChanged += gcnew System::EventHandler(this, &Form1::textBoxX1X2_TextChanged);
            this->textBoxX2->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form1::textBoxX1X2_KeyPress);
            // 
            // buttonCalc
            // 
            this->buttonCalc->Font = (gcnew System::Drawing::Font(L"Verdana", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->buttonCalc->Location = System::Drawing::Point(29, 226);
            this->buttonCalc->Name = L"buttonCalc";
            this->buttonCalc->Size = System::Drawing::Size(137, 57);
            this->buttonCalc->TabIndex = 1;
            this->buttonCalc->Text = L"Calc";
            this->buttonCalc->UseVisualStyleBackColor = true;
            this->buttonCalc->Click += gcnew System::EventHandler(this, &Form1::buttonCalc_Click);
            // 
            // labelA
            // 
            this->labelA->AutoSize = true;
            this->labelA->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->labelA->Location = System::Drawing::Point(25, 14);
            this->labelA->Name = L"labelA";
            this->labelA->Size = System::Drawing::Size(41, 20);
            this->labelA->TabIndex = 3;
            this->labelA->Text = L"A = ";
            // 
            // labelB
            // 
            this->labelB->AutoSize = true;
            this->labelB->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->labelB->Location = System::Drawing::Point(25, 83);
            this->labelB->Name = L"labelB";
            this->labelB->Size = System::Drawing::Size(41, 20);
            this->labelB->TabIndex = 4;
            this->labelB->Text = L"B = ";
            // 
            // labelC
            // 
            this->labelC->AutoSize = true;
            this->labelC->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->labelC->Location = System::Drawing::Point(25, 153);
            this->labelC->Name = L"labelC";
            this->labelC->Size = System::Drawing::Size(41, 20);
            this->labelC->TabIndex = 4;
            this->labelC->Text = L"C = ";
            // 
            // labelX1
            // 
            this->labelX1->AutoSize = true;
            this->labelX1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->labelX1->Location = System::Drawing::Point(277, 14);
            this->labelX1->Name = L"labelX1";
            this->labelX1->Size = System::Drawing::Size(51, 20);
            this->labelX1->TabIndex = 3;
            this->labelX1->Text = L"X1 = ";
            // 
            // labelX2
            // 
            this->labelX2->AutoSize = true;
            this->labelX2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->labelX2->Location = System::Drawing::Point(277, 83);
            this->labelX2->Name = L"labelX2";
            this->labelX2->Size = System::Drawing::Size(51, 20);
            this->labelX2->TabIndex = 3;
            this->labelX2->Text = L"X2 = ";
            // 
            // labelStatus
            // 
            this->labelStatus->AutoSize = true;
            this->labelStatus->Font = (gcnew System::Drawing::Font(L"Times New Roman", 15.75F, System::Drawing::FontStyle::Italic, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->labelStatus->Location = System::Drawing::Point(12, 307);
            this->labelStatus->Name = L"labelStatus";
            this->labelStatus->Size = System::Drawing::Size(154, 23);
            this->labelStatus->TabIndex = 5;
            this->labelStatus->Text = L"введите данные";
            // 
            // TestQ1
            // 
            this->TestQ1->Font = (gcnew System::Drawing::Font(L"Verdana", 14.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->TestQ1->Location = System::Drawing::Point(632, 226);
            this->TestQ1->Name = L"TestQ1";
            this->TestQ1->Size = System::Drawing::Size(96, 57);
            this->TestQ1->TabIndex = 6;
            this->TestQ1->Text = L"TestQ";
            this->TestQ1->UseVisualStyleBackColor = true;
            this->TestQ1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
            // 
            // progressBar1
            // 
            this->progressBar1->BackColor = System::Drawing::Color::White;
            this->progressBar1->Location = System::Drawing::Point(343, 153);
            this->progressBar1->Name = L"progressBar1";
            this->progressBar1->Size = System::Drawing::Size(385, 31);
            this->progressBar1->TabIndex = 7;
            this->progressBar1->Value = 100;
            // 
            // Test
            // 
            this->Test->AutoSize = true;
            this->Test->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
                static_cast<System::Byte>(204)));
            this->Test->Location = System::Drawing::Point(277, 159);
            this->Test->Name = L"Test";
            this->Test->Size = System::Drawing::Size(44, 20);
            this->Test->TabIndex = 8;
            this->Test->Text = L"Test";
            // 
            // Form1
            // 
            this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
            this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
            this->ClientSize = System::Drawing::Size(760, 339);
            this->Controls->Add(this->Test);
            this->Controls->Add(this->progressBar1);
            this->Controls->Add(this->TestQ1);
            this->Controls->Add(this->labelA);
            this->Controls->Add(this->labelB);
            this->Controls->Add(this->labelC);
            this->Controls->Add(this->labelX1);
            this->Controls->Add(this->labelX2);
            this->Controls->Add(this->labelStatus);
            this->Controls->Add(this->buttonCalc);
            this->Controls->Add(this->textBoxA);
            this->Controls->Add(this->textBoxB);
            this->Controls->Add(this->textBoxC);
            this->Controls->Add(this->textBoxX1);
            this->Controls->Add(this->textBoxX2);
            this->Name = L"Form1";
            this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
            this->ResumeLayout(false);
            this->PerformLayout();
 
        }
#pragma endregion
 
    private: bool IsEmptyABC()
             {
                
                 return (textBoxA->Text == ""  && textBoxB->Text == ""  && textBoxC->Text == ""); 
             }
    
    private: void HideX1()
             {
                 labelX1->Visible = false;
                 textBoxX1->Visible = false;
             }
    private: void HideX2()
             {
                 labelX2->Visible = false;
                 textBoxX2->Visible = false;
             }
    private: void HideX1X2()
             {
                 HideX1();
                 HideX2();
             }
    private: void X1Show(String^ SText)
             {
                 labelX1->Visible = true;
                 textBoxX1->Visible = true;
                 textBoxX1->Text = SText;
             }
    private: void X2Show(String^ SText)
             {
                 labelX2->Visible = true;
                 textBoxX2->Visible = true;
                 textBoxX2->Text = SText;
             }
    private: void StatusShow(String^ SText)
             {
                 labelStatus->ForeColor = SystemColors::ControlText;
                 labelStatus->Text = SText;
             }
    private: void StatusShowError(String^ SText)
             {
                 labelStatus->ForeColor = Drawing::Color::Red;
                 labelStatus->Text = SText;
             }
    private: void TextChanged()
             {
                 HideX1X2();
                 if (IsEmptyABC()) StatusShow("введите данные");
                 else StatusShow("производится ввод данных");
             }
    private: String^ complex2String(complex <double> com)
             {
                 String^ sBuf = "";
                 if (com.imag() >= 0)
                     sBuf = Convert::ToString(com.real())+"+" + Convert::ToString(com.imag()) + "i";
                 else
                     sBuf = Convert::ToString(com.real()) + Convert::ToString(com.imag()) + "i";
                 return sBuf;
             }
    private: bool IsDouble(String^ input)
             {
                 using namespace System::Text::RegularExpressions;
                 String^ pattern = "\\A\\s*[+-]?\\s*\\d+([,]\\d+)?\\s*\\Z";
                 Match^ m = Regex::Match(input, pattern);
                 return m->Success;
             }
    private: double StringToDouble(String^ sText)
             {
                 double res = 0.0;
                 if (String::IsNullOrEmpty(sText)) return 0.0;
                 if (IsDouble(sText))
                    {if (Double::TryParse(sText,res)) return res;}
                 else
                     throw L"double StringToDouble(String^ sText)";
             }
    private: void CalcQuadratic()
             {
                 double a,b,c;
                 try
                 {
                     a = StringToDouble(textBoxA->Text);
                     b = StringToDouble(textBoxB->Text);
                     c = StringToDouble(textBoxC->Text);
                 }
                 catch (...)
                 {
                     StatusShowError("double StringToDouble(String^ sText)");
                     return;
                 }
                 Quadratic qr(a,b,c);
                 QuadraticResult Result = qr.Calc();
                 String^ Text = qr.QuadraticResultToString(Result);
                 switch (Result) 
                 {
                 case InfinityRoot:
                    HideX1X2();
                     StatusShowError(Text);
                     break;
                 case NoRoot:
                     HideX1X2();
                     StatusShowError(Text);
                     break;
                 case OneRealRoot:
                     X1Show(qr.getX1().ToString());
                     StatusShow(Text);
                     break;
                 case TwoRealRoot:
                     X1Show(qr.getX1().ToString());
                     X2Show(qr.getX2().ToString());
                     StatusShow(Text);
                     break;
                 case TwoComplexRoot:
                     X1Show(complex2String(qr.getXC1()));
                     X2Show(complex2String(qr.getXC2()));
                     StatusShow(Text);
                     break;
                 }
             }
    private: void TestQuadratic()
             {
 
             }
    private: System::Void buttonCalc_Click(System::Object^  sender, System::EventArgs^  e) {
                 if (IsEmptyABC())
                 {
                     StatusShow("введите данные");
                 } 
                 else 
                 {
                     CalcQuadratic();
                 }
             }
    private: System::Void textBox_TextChanged(System::Object^  sender, System::EventArgs^  e) {
                 TextChanged();
             }
    private: System::Void textBox_KeyPress(System::Object^  sender, System::Windows::Forms::KeyPressEventArgs^  e) {
                 if (e->KeyChar == L'.') e->KeyChar = L',';
                 wchar_t ch = e->KeyChar;
                 TextBox^ tb = dynamic_cast<TextBox^>(sender);
                 if ((ch >= L'0')&&(ch <= L'9')) return;
                 if ((ch == L',')&&(tb->Text->IndexOf(ch) == -1)
                     && (tb->Text =="" || tb->SelectionStart != 0)) return;
                 if ((ch == L'+')||(ch == L'-'))
                 {
                     if(tb->Text->IndexOf(ch) == -1
                         && (tb->Text =="" || tb->SelectionStart == 0)) return;
                 }
                 if ((ch == '\b')||(ch == '\r')||(ch == '\t')) return;
                 //Все остальные знаки игнорировать
                 e->Handled = true;
             }
 
    private: System::Void textBoxX1X2_TextChanged(System::Object^  sender, System::EventArgs^  e) {
                 
             }
    private: System::Void textBoxX1X2_KeyPress(System::Object^  sender, System::Windows::Forms::KeyPressEventArgs^  e) {
                 wchar_t ch = e->KeyChar;
                 if ((ch == '\r')||(ch == '\t')) return;
                 //Все остальные знаки игнорировать
                 e->Handled = true;
             }
    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
                 HideX1X2();
                 StatusShow("введите данные");
             }
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
 
             }
};
}
Quadratic.h
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#pragma once
#include "stdafx.h"
#include <complex>
 
 
namespace Quadratics 
{
    using namespace System;
    using namespace std;
 
    enum QuadraticResult 
    {
        NoResult,
        TwoRealRoot,
        TwoComplexRoot,
        OneRealRoot,
        NoRoot,
        InfinityRoot,
    };
 
    class Quadratic
    {
    public:
        Quadratic(double pA,double pB, double pC):a(pA),b(pB),c(pC),CalcResult(NoResult){};
        System::String^ QuadraticResultToString(QuadraticResult pResult);
        double getX1();
        double getX2();
        double a,b,c;               
        double D;                   
        double x1,x2;
        complex <double> getXC1();
        complex <double> getXC2();      
        complex <double> xc1;
        complex <double> xc2;   
        QuadraticResult Calc();
        QuadraticResult CalcResult; 
    };
}
Quadratic.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "stdafx.h"
#include <iostream>
#include <complex>
#include "Quadratic.h"
 
namespace Quadratics
{
    using namespace System;
    using namespace std;
 
    
 
String^ Quadratic::QuadraticResultToString(QuadraticResult pResult)
{
    switch (pResult)
        {
        case NoResult: return "расчет не произведен";
        case TwoRealRoot: return "два действительных корня";
        case TwoComplexRoot: return "два комплексных корня";
        case OneRealRoot: return "один действительный корень";
        case NoRoot: return "нет корней";
        case InfinityRoot: return "бесконечное множество корней";
        default:
            return "default";
        }   
    };
 
    QuadraticResult Quadratic::Calc()
    {
        if (a == 0.0)
        {
            if (b == 0.0)
            {
                if (c == 0.0)
                    CalcResult = InfinityRoot;
                else
                {
                    CalcResult = NoRoot;
                }
            } 
            else
            { 
                x1 = -c/b;
                CalcResult = OneRealRoot;
            }
        }
        else
        { 
            D = b*b - 4*a*c;
            if (D > 0.0) 
            {
                x1 = (-b + Math::Sqrt(D))/(2*a);
                x2 = (-b - Math::Sqrt(D))/(2*a);
                CalcResult = TwoRealRoot;
            } 
            else 
            {
                if (D == 0.0)
                {
                    x1 = x2 = -b/(2*a);
                    CalcResult = TwoRealRoot;
                }
                else 
                {
                    double x2re = -b/(2*a);
                    double x1re = x2re;
                    double x2im = Math::Sqrt(-D)/(2*a);
                    double x1im = -x2im;
                    xc1 = complex <double> (x1re,x1im);
                    xc2 = complex <double> (x2re,x2im);
                    CalcResult = TwoComplexRoot;
                }
            }
        }
        return CalcResult;
    }
 
    double Quadratic::getX1()
    {
        if (CalcResult == TwoRealRoot || CalcResult == OneRealRoot) return x1;
        else throw CalcResult;
    }
    double Quadratic::getX2()
    {
        if (CalcResult == TwoRealRoot) return x2;
        else throw CalcResult;
    }
    complex <double> Quadratic::getXC1()
    {
        if (CalcResult == TwoComplexRoot) return xc1;
        else throw CalcResult;
    }
    complex <double> Quadratic::getXC2()
    {
        if (CalcResult == TwoComplexRoot) return xc2;
        else throw CalcResult;
    }
}
Решение квадратного уравнения.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Решение квадратного уравнения.cpp: главный файл проекта.
 
#include "stdafx.h"
#include "Form1.h"
 
using namespace РешениеКвадратногоУравнения;
 
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
    // Включение визуальных эффектов Windows XP до создания каких-либо элементов управления
    Application::EnableVisualStyles();
    Application::SetCompatibleTextRenderingDefault(false); 
 
    // Создание главного окна и его запуск
    Application::Run(gcnew Form1());
    return 0;
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
29.11.2020, 16:22
Помогаю со студенческими работами здесь

Тестирование системного класса Integer
Здравствуйте, стоит задача написать программу тестирования всех констант, включенных в класс (если они имеются) и методов, принадлежащих...

«Тестирование коллектива». Пусть целочисленная матрица размера n×m содержит информацию об учениках некоторого класса из
«Тестирование коллектива». Пусть целочисленная матрица размера n×m содержит информацию об учениках некоторого класса из п человек: j-я...

Удаленное тестирование приложение/Пересылка на тестирование
Если кто-то написал приложение под андроид и захочет показать другому человеку, то достаточно отослать apk. А как обстоит с этим дело в...

Unit -тестирование или автоматизированное тестирование
Доброго времени суток. Я программирую «для себя» второй год, на выходе получаются разного рода приложения от постоянно подающих с...

Тестирование (или Юнит тестирование)
Доброго времени суток, возник такой вопрос, раньше встречался на фронтенде с js тестированием, сейчас задался вопросом по поводу...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru