Реализуйте класс для работы с комплексным числами (ComplexNumber)
23.05.2014, 02:04. Показов 1539. Ответов 2
Задание звучит так:
Реализуйте класс для работы с комплексным числами (ComplexNumber) удовлетворяющий следующим требованиям:
• Класс должен содержать два свойства типа double для хранения действительной и мнимой частей. Называться они должны Real и Imaginary.
• Класс должен иметь два конструктора. Первый принимает значение действительной (real) части (мнимая часть должна равняться 0). Второй принимает значение действительной (real) и мнимой (imaginary) части;
• Класс должен реализовывать операторы сложения (+) и вычитания (-);
o Операторы «+»и «-» должны работать как с комплексными числами так и числами с плавающей точкой. В последнем случае следует выполнять операцию так как будто мнимая часть равна нулю.
• Класс должен реализовывать операторы равенства (==) и неравенства (!=),а также переопределять метод Equals();
• Он должен переопределять метод ToString();
o Вызов ToString() должен возвращать алгебраическую форму числа то есть строку вида «реальная + iмнимая)»
• Он должен реализовывать интерфейс IEquatable <ComplexNumber >;
• Он должен реализовывать интерфейс IFormattable:
o Для формата P (Pair, пара) должна возвращаться строка вида «(реальная, мнимая)»;
o Для формата A (Algebraic, алгебраическая форма) должна возвращаться строка вида «реальная + iмнимая)». Обратите внимание что, когда мнимая часть отрицательная, строка должна иметь вид «реальная - iмнимая)»;
o Если в качестве формата передано значение null, то используем формат A;
o Дополнительное задание: при использовании неизвестного формата должно генерироваться исключение FormatException:
Вот что я смог сделать, но не работает, помогите разобраться где я допустил ошибку, заранее благодарен.
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
| using System;
class Program
{
class ComplexNumber : IEquatable<ComplexNumber>, IFormattable
{
public double Real { get; set; }
public double Imaginary { get; set; }
public ComplexNumber()
{
}
public ComplexNumber(double real)
{
Real = real;
Imaginary = 0;
}
public ComplexNumber(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
public static ComplexNumber operator +(ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber(a.Imaginary + b.Imaginary, a.Real + b.Real);
}
public static ComplexNumber operator -(ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber(a.Imaginary - b.Imaginary, a.Real - b.Real);
}
public static bool operator ==(ComplexNumber a, ComplexNumber b)
{
if (ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
return false;
return true;
}
public static bool operator !=(ComplexNumber a, ComplexNumber b)
{
return !(a == b);
}
public static ComplexNumber operator +(ComplexNumber a, double k)
{
return new ComplexNumber()
{
Imaginary = a.Imaginary,
Real = a.Real + k
};
}
public static ComplexNumber operator -(ComplexNumber a, double k)
{
return new ComplexNumber(a.Imaginary, a.Real - k);
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
ComplexNumber n = obj as ComplexNumber;
if ((Object)n == null)
return false;
return true;
}
public bool Equals(ComplexNumber n)
{
if ((object)n == null)
return false;
return true;
}
public override int GetHashCode()
{
return (int)Imaginary ^ (int)Real;
}
public override string ToString()
{
return string.Format("{0} + I {1}", Real, Imaginary);
}
public string ToString(string format, IFormatProvider formatProvider)
{
switch (format.ToUpperInvariant())
{
case "P":
return string.Format("({0}, {1})", Real, Imaginary);
case "A":
return string.Format("({0} + i{1})", Real, Imaginary);
default:
throw new FormatException(String.Format("Формат строки: {0} - не поддерживается", format));
}
}
}
static void Main()
{
ComplexNumber x = new ComplexNumber(10.5);
ComplexNumber y = null;
if (y == null)
{
y = new ComplexNumber(7, 8.1);
ComplexNumber z = x + y;
Console.WriteLine(z); // 17,5+i8,1
z -= 20;
Console.WriteLine(z); // -2,5+i8,1
z.Real += 13;
z.Imaginary -= 8.1;
Console.WriteLine(z); // 10,5
if (z == x && z != y)
{
Console.WriteLine("{0:A}", z - y); // 3,5-i8,1
Console.WriteLine("{0:P}", z - y); // (3,5, -8,1)
}
}
Console.ReadKey();
}
} |
|
Добавлено через 8 часов 32 минуты
Рабочий вариант:
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
| using System;
using System.Globalization;
class Program
{
class ComplexNumber : IEquatable<ComplexNumber>, IFormattable
{
public double Real { get; set; }
public double Imaginary { get; set; }
public ComplexNumber()
{
}
public ComplexNumber(double real)
{
Real = real;
Imaginary = 0;
}
public ComplexNumber(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
public static ComplexNumber operator +(ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber(a.Imaginary + b.Imaginary, a.Real + b.Real);
}
public static ComplexNumber operator -(ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber(a.Imaginary - b.Imaginary, a.Real - b.Real);
}
public static bool operator ==(ComplexNumber a, ComplexNumber b)
{
if (ReferenceEquals(a, b))
return true;
if (((object)a == null) || ((object)b == null))
return false;
return true;
}
public static bool operator !=(ComplexNumber a, ComplexNumber b)
{
return !(a == b);
}
public static ComplexNumber operator +(ComplexNumber a, double k)
{
return new ComplexNumber()
{
Imaginary = a.Imaginary,
Real = a.Real + k
};
}
public static ComplexNumber operator -(ComplexNumber a, double k)
{
return new ComplexNumber(a.Imaginary, a.Real - k);
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
ComplexNumber n = obj as ComplexNumber;
if ((Object)n == null)
return false;
return true;
}
public bool Equals(ComplexNumber n)
{
if ((object)n == null)
return false;
return true;
}
public override int GetHashCode()
{
return (int)Imaginary ^ (int)Real;
}
public override string ToString()
{
return string.Format("{0} + I {1}", Real, Imaginary);
}
public string ToString(string format, IFormatProvider formatProvider)
{
switch (format.ToUpperInvariant())
{
case "P":
return string.Format("({0}, {1})", Real, Imaginary);
case "A":
return string.Format("({0} + i{1})", Real, Imaginary);
default:
throw new FormatException(String.Format("Формат строки: {0} - не поддерживается", format));
}
}
}
static void Main()
{
ComplexNumber x = new ComplexNumber(10.5);
ComplexNumber y = null;
CultureInfo ru = new CultureInfo("ru-RU");
if (y == null)
{
y = new ComplexNumber(7, 8.1);
ComplexNumber z = x + y;
Console.WriteLine(z.ToString("P", ru)); // 17,5+i8,1
z -= 20;
Console.WriteLine(z.ToString("P", ru)); // -2,5+i8,1
z.Real += 13;
z.Imaginary -= 8.1;
Console.WriteLine(z.ToString("P", ru)); // 10,5
if (z == x && z != y)
{
Console.WriteLine("{0:A}", z - y); // 3,5-i8,1
Console.WriteLine("{0:P}", z - y); // (3,5, -8,1)
}
}
Console.ReadKey();
}
} |
|
0
|