## 2018年1月2日火曜日

### C# - 演算子のオーバーロード(Equals 演算子、operator キーワード、等価演算子(==)、有理数、既約、最大公約数)

コード

```using System;

namespace Sample9
{
class Fraction
{
private int numerator;
private int denominator;

private static int gcd(int a, int b)
{
int x = a < 0 ? -a : a;
int y = b < 0 ? -b : b;
int n = x < y ? x : y;
for (int i = n; i > 0 ; i--)
{
if (x % i == 0 && y % i == 0)
{
return i;
}
}
return 1;
}
public Fraction(int numerator, int denominator)
{
int d = gcd(numerator, denominator);
this.numerator = numerator / d;
this.denominator = denominator / d;
}
public static bool operator ==(Fraction lhs, Fraction rhs)
{
if (lhs.denominator == rhs.denominator && lhs.numerator == rhs.numerator)
{
return true;
}
return false;
}
public static bool operator !=(Fraction lhs, Fraction rhs)
{
return !(lhs == rhs);
}
public override bool Equals(Object o)
{
if (! (o is Fraction))
{
return false;
}
return this == (Fraction)o;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
return string.Format("{0}/{1}", numerator, denominator);
}
}
class Program
{
static void Main(string[] args)
{
Fraction a = new Fraction(3, 4);
Fraction b = new Fraction(6, 8);
Fraction c = new Fraction(-9, 12);
Fraction[] nums = { a, b, c };

foreach (var x in nums)
{
Console.WriteLine(x);
foreach (var y in nums)
{
Console.WriteLine("\t{0}: {1}", y, x == y);
}
}
}
}
}
```

```3/4
3/4: True
3/4: True
-3/4: False
3/4
3/4: True
3/4: True
-3/4: False
-3/4
3/4: False
3/4: False
-3/4: True

Press any key to continue...
```