numerator & denominator is squared when I multiply 2 times
Fraction file:
using System;
namespace MathLib.Fraction
{
public struct Fraction
{
// Private Member
static int prNumer;
static int prDenom;
// Constructor
public Fraction(int _numer, int _denom)
{
if(_denom == 0)
{
throw new ArgumentException("Denominator cannot be Zero.", "_denom");
}
prNumer = _numer;
prDenom = _denom;
}
// Other
public int GetNumer()
{
return prNumer;
}
public int GetDenom()
{
return prDenom;
}
public override string ToString()
{
return prNumer + "/" + prDenom;
}
// Operator Overloading
public static Fraction operator *(Fraction left, Fraction right)
{
int numer = left.GetNumer() * right.GetNumer();
int denom = left.GetDenom() * right.GetDenom();
return new Fraction(numer, denom);
}
}
}
Main file:
using System;
using MathLib;
using MathLib.Fraction;
namespace MathLibTest
{
class Program
{
static void Main(string[] args)
{
Fraction a = new Fraction(3, 5);
Fraction b = new Fraction(6, 8);
Console.WriteLine(a * b); // 36/64
Console.WriteLine(a * b); // 1296/4096 what I expected is: 36/64 again
}
}
}
What I’m trying to accomplish: Just making a simple math library that I will use at future. I’m not joking I’ll use this in the future 🙂
Approach that I tried: Rewriting the entire fraction class, 30 minutes of searching what is wrong and still wrong
// Sorry for my bad english 🙂
>Solution :
static int prNumer;
static int prDenom;
Remove the static
; static
means there is only one value shared over all instances (unless it is [ThreadStatic]
). You want a per-instance value, so: remove static
.
I would also recommend marking the fields readonly
, and using readonly struct
if you’re using a recent C# version.
Full recommended version, for reference:
public readonly struct Fraction : IEquatable<Fraction>
{
public int Numerator { get; }
public int Denominator { get; }
public Fraction(int numererator, int denominator)
{
if (denominator == 0)
{
throw new ArgumentException("Denominator cannot be Zero.", nameof(denominator));
}
// TODO: lowest common denominator
Numerator = numererator;
Denominator = denominator;
}
public override string ToString() => $"{Numerator}/{Denominator}";
public static Fraction operator *(Fraction left, Fraction right)
=> new Fraction(left.Numerator * right.Numerator, left.Denominator * right.Denominator);
public override int GetHashCode() => HashCode.Combine(Numerator, Denominator);
public override bool Equals([NotNullWhen(true)] object obj)
=> obj is Fraction other && Equals(other);
public bool Equals(Fraction other)
=> Numerator == other.Numerator && Denominator == other.Denominator;
}