Having trouble in c# fraction calculator -
i have assignment due tomorrow has add , subtract fractions whole numbers, , i'm getting bit confused these numbers, , math isn't helping either.
it's performing math correctly, keeps putting 1 whole variable when should 0 , can't figure out life of me why.
here's fraction.cs:
class fraction { int num, den, whole, newnum; public fraction(int numerator, int denominator, int whole = 0) { this.num = numerator; this.den = denominator; this.whole = whole; } public fraction add(fraction other) { int temp1 = num, temp2 = den; if (math.abs(this.whole) > 0) { newnum = temp2 * whole; newnum = +temp1; temp1 = newnum; } if (math.abs(other.whole) > 0) { other.newnum = other.den * other.whole; other.newnum = +other.num; other.num = other.newnum; } temp1 = temp1 * other.den + temp2 * other.num; temp2 = temp2 * other.den; if (temp1 == temp2 || temp1 > temp2) { whole = temp1 / temp2; temp1 = temp1 % temp2; } fraction newfrac = new fraction(temp1, temp2, whole); return newfrac; } }
and inside program.cs here's test:
fraction fra1 = new fraction(1, 2); fraction fra2 = new fraction(3, 4, 1); fraction fra3 = fra1.add(fra2); console.writeline("fraction 1: " + fra1); console.writeline("fraction 2: " + fra2); console.writeline("{0} + {1} = {2}", fra1, fra2, fra3);
and here's i'm getting result:
any appreciated! in advanced. austen
i think problem line:
whole = temp1 / temp2
it seems you're accidently modifying whole
value of current instance. that's what's causing fra1
'magically' change 1/2
1 1/2
. use temporary variable instead , should fix problem, i'd recommend making similar adjustments avoid accidentally modifying fields of other
removing newnum
field apparently there temporary placeholder calculations.
if intend make class immutable, i'd recommend making each of fields readonly
avoid these errors.
Comments
Post a Comment