開発環境
- OS: macOS High Sierra - Apple
- IDE(統合開発環境): Visual Studio for Mac
- プログラミング言語: C#
初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)、日向 俊二 (翻訳)、オライリージャパン)の12章(演算子のオーバーロード)、12.3(Equals 演算子)、補足情報(読者の練習問題).を取り組んでみる。
コード
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);
}
}
}
}
}
入出力結果(Terminal)
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...
0 コメント:
コメントを投稿