Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.75/8: Рейтинг темы: голосов - 8, средняя оценка - 4.75
370 / 351 / 193
Регистрация: 31.03.2013
Сообщений: 2,586
1

Реализуйте класс для работы с комплексным числами (ComplexNumber)

23.05.2014, 02:04. Показов 1539. Ответов 2
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Задание звучит так:
Реализуйте класс для работы с комплексным числами (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
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
23.05.2014, 02:04
Ответы с готовыми решениями:

Реализуйте класс для работы с комплексным числами (ComplexNumber)
ПОМОГИТЕ ПОЖАЛУЙСТА РЕШИТЬ с ИНТЕРФЕЙСАМИ ЗАДАЧУ!!! Реализуйте класс для работы с комплексным...

Класс для работы с комплексными числами
Описать класс для работы с комплексными числами. Обеспечить следующие возможности:  ввод...

Класс для работы с длинными числами
курсач горит!!!!! срочно нужно написать класс для работы с длинными числами. помогите кто чем...

Класс для работы с большими числами
Всем привет,можете подсказать как можно реализовать класс для работы с большими числами(*,+,-,/)

2
116 / 116 / 70
Регистрация: 10.11.2013
Сообщений: 445
23.05.2014, 15:27 2
Цитата Сообщение от Midian Посмотреть сообщение
C#
1
2
3
4
5
6
7
8
9
public ComplexNumber(double real){
 Real = real;
 Imaginary = 0;
}
public ComplexNumber(double real, double imaginary)
 {
 Real = real;
 Imaginary = imaginary;
}
Можно обойтись одним конструктором с параметром по умолчанию

C#
1
2
3
4
5
public ComplexNumber(double real, double imaginary = 0)
{
 Real = real;
 Imaginary = imaginary;
}
И, по-моему, как-то странно перекрыт оператор сравнения.
0
370 / 351 / 193
Регистрация: 31.03.2013
Сообщений: 2,586
24.05.2014, 03:07  [ТС] 3
Получилось как-то так:
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
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.Real + b.Real, a.Imaginary + b.Imaginary);
        }
 
        public static ComplexNumber operator -(ComplexNumber a, ComplexNumber b)
        {
            return new ComplexNumber(a.Real - b.Real, a.Imaginary - b.Imaginary);
        }
 
        public static bool operator ==(ComplexNumber a, ComplexNumber b)
        {
            if (ReferenceEquals(a, b))
                return true;
            return a.Real == b.Real && a.Imaginary == b.Imaginary;
        }
 
        public static bool operator !=(ComplexNumber a, ComplexNumber b)
        {
            return a.Real != b.Real || a.Imaginary != b.Imaginary;
        }
 
        public static ComplexNumber operator +(ComplexNumber a, double k)
        {
            return new ComplexNumber(a.Real + k, a.Imaginary);
        }
 
        public static ComplexNumber operator -(ComplexNumber a, double k)
        {
            return new ComplexNumber(a.Real - k, a.Imaginary);
        }
 
        public override bool Equals(Object obj)
        {
            if (obj == null)
                return false;
            ComplexNumber p = obj as ComplexNumber;
            if ((System.Object)p == null)
                return false;
            return (Real == p.Real) && (Imaginary == p.Imaginary);
        }
 
        public bool Equals(ComplexNumber p)
        {
            if ((object)p == null)
                return false;
            return (Real == p.Real) && (Imaginary == p.Imaginary);
        }
 
        public override string ToString()
        {
            return this.ToString("A", CultureInfo.CurrentCulture);
        }
 
        public string ToString(string format)
        {
            return this.ToString(format, CultureInfo.CurrentCulture);
        }
 
        public string ToString(string format, IFormatProvider provider)
        {
            if (String.IsNullOrEmpty(format)) format = "A";
            if (provider == null) provider = CultureInfo.CurrentCulture;
            switch (format.ToUpperInvariant())
            {
                case "P":
                    return string.Format(provider, "({0}, {1})", Real, Imaginary);
                case "A":
                     if (Real == 0)
                         return string.Format(provider, "(i{1})", Imaginary);
                    else if (Imaginary == 0)
                         return string.Format(provider, "({0})", Real);
                     else return string.Format(provider, "({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();
    }
}
0
24.05.2014, 03:07
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
24.05.2014, 03:07
Помогаю со студенческими работами здесь

Класс для работы со сверхбольшими числами
Составить описание класса для работы со сверхбольшими числами. Обеспечить выполнение основных...

Реализовать класс Complex для работы с комплексными числами
Комплексное число представляются парой действительных чисел (a,b), где a-действительная часть,...

Создать класс Complex для работы с комплексными числами
Класс должен содержать: 1.1 Поля. 1.1.1 int a // действительная часть 1.1.2 int b // мнимая...

Создать класс Fraction для работы с дробными числами
Прошу помочь! Задание: Создать класс Fraction для работы с дробными числами. Число должно...


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

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru