【发布时间】:2015-04-30 22:40:09
【问题描述】:
我在尝试让我的分数计算器工作时遇到了麻烦。我正在尝试简化工作,它可以正确地简化正分数,但是如果我要输入负分数,它不会简化它,我不确定我做错了什么,我已经阅读在它上面多次(Gcd 和 Reduce 函数)。
我对所有这些都是新手,感谢任何帮助。
我的 Reduce 和 GCD 函数:
public int gcd()
{
// assigned x and y to the answer Numerator/Denominator, as well as an
// empty integer, this is to make code more simple and easier to read
int x = answerNumerator;
int y = answerDenominator;
int m;
// check if numerator is greater than the denominator,
// make m equal to denominator if so
if (x > y)
m = y;
else
// if not, make m equal to the numerator
m = x;
// assign i to equal to m, make sure if i is greater
// than or equal to 1, then take away from it
for (int i = m; i >= 1; i--)
{
if (x % i == 0 && y % i == 0)
{
//return the value of i
return i;
}
}
return 1;
}
public void Reduce()
{
try
{
//assign an integer to the gcd value
int gcdNum = gcd();
if (gcdNum != 0)
{
answerNumerator = answerNumerator / gcdNum;
answerDenominator = answerDenominator / gcdNum;
}
if (answerDenominator < 0)
{
answerDenominator = answerDenominator * -1;
answerNumerator = answerNumerator * -1;
}
}
catch (Exception exp)
{
// display the following error message
// if the fraction cannot be reduced
throw new InvalidOperationException(
"Cannot reduce Fraction: " + exp.Message);
}
}
【问题讨论】:
-
一般性评论:如果您的函数采用参数而不是依赖和作用于全局变量,您的函数会更好。
-
你能举一个“负分数”的例子吗?是否只是
answerNumerator或answerDenominator小于零? -
我的意思是负分数。我在计算器中输入 1 1/2 - 4 1/4 得到 -2 -6/8 而不是 -2 3/4。
-
你这是什么意思?
-
该代码未显示,但在内部您只存储分子和分母,对吗?因此,即使您显示
1 1/2,在内部您也将其存储为numerator = 3; denominator = 2?
标签: c# calculator simplify