-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathIComparable.cs
More file actions
58 lines (50 loc) · 1.21 KB
/
IComparable.cs
File metadata and controls
58 lines (50 loc) · 1.21 KB
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
using System;
class Fraction : IComparable
{
int z, n;
public Fraction(int z, int n)
{
this.z = z;
this.n = n;
}
public static Fraction operator +(Fraction a, Fraction b)
{
return new Fraction(a.z * b.n + a.n * b.z, a.n * b.n);
}
public static Fraction operator *(Fraction a, Fraction b)
{
return new Fraction(a.z * b.z, a.n * b.n);
}
public int CompareTo(object obj)
{
Fraction f = (Fraction)obj;
if ((float)z / n < (float)f.z / f.n)
return -1;
else if ((float)z / n > (float)f.z / f.n)
return 1;
else return 0;
}
public override string ToString()
{
return z + "/" + n;
}
}
class Test
{
static void Main(string[] arg)
{
Fraction[] a =
{
new Fraction(5,2),
new Fraction(29,6),
new Fraction(4,5),
new Fraction(10,8),
new Fraction(34,7)
};
Array.Sort(a);
Console.WriteLine("Implementing the IComparable Interface in Displaying Fractions : ");
foreach (Fraction f in a) Console.WriteLine(f + " ");
Console.WriteLine();
Console.ReadLine();
}
}