编写Greatest Common Divisor方法时遇到问题
本文关键字:遇到 问题 方法 Divisor Greatest Common 编写 | 更新日期: 2023-09-27 18:29:02
我正在创建一个计算器程序,需要创建GreatestCommononDivisor
和ReduceFraction
方法;但是我的GreatestCommonDivisor
方法没有得到正确的值,我不知道为什么。
有人能在正确的方向上提供任何指导或帮助吗?
public static void ProcessReduceFraction()
{
Int32 numerator, denominator, reducedNumerator, reducedDenominator;
numerator = GetPostiveNonZeroInteger("Please Enter Non-Zero Postive Numerator");
denominator = GetPostiveNonZeroInteger("Please Enter Non-Zero Postive Denominator");
reducedNumerator = numerator / GreatestCommonDivisor(denominator, numerator);
reducedDenominator = denominator / GreatestCommonDivisor(numerator, denominator);
Console.WriteLine("{0}/{1} can be reduced to: {2}/{3} ", numerator, denominator, reducedNumerator, reducedDenominator);
Console.ReadLine();
}
public static Int32 GreatestCommonDivisor(Int32 r, Int32 n)
{
Int32 remainder ,dividend, divisor, pervremainder;
dividend = Math.Max(Math.Abs(n),Math.Abs(r));
divisor = Math.Min(Math.Abs(n), Math.Abs(r));
remainder = dividend % divisor;
pervremainder = divisor;
// Pull out remainders.
while (remainder == 0)
{
if (remainder!= 0)
{
dividend = divisor;
divisor = remainder;
pervremainder = remainder;
remainder = dividend % divisor;
}
}
return pervremainder;
}
public static void ProcessGreatestCommonDivisor()
{
Int32 firstnumber, secondnumber, greatestcommondivisor;
firstnumber = GetPostiveNonZeroInteger("Plesae Enter Non-Zero Postive First Number");
//firstnumber = Int32.Parse(Console.ReadLine());
secondnumber = GetPostiveNonZeroInteger("Please Enter Non-Zero Postive Secound Number");
//secoundnumber = Int32.Parse(Console.ReadLine());
greatestcommondivisor = GreatestCommonDivisor(secondnumber, firstnumber);
//greatestcommondivisor = Int32.Parse(Console.ReadLine());
Console.WriteLine("The Greatest Common Divisor of {0} and {1} is: {2} ",
firstnumber,secondnumber, greatestcommondivisor);
Console.ReadLine();
}
public static Int32 GetPostiveNonZeroInteger(String prompt)
{
Int32 n;
Console.WriteLine(prompt);
n = Int32.Parse(Console.ReadLine());
while (n <= 0)
{
Console.WriteLine("Error: enter non-zero postive value");
Console.WriteLine(prompt);
n = Int32.Parse(Console.ReadLine());
}
return n;
}
}
因为你提到了计算最大公约数。我认为一个简单的方法是
public static int gcd(int dividend, int divisor)
{
while (divisor != 0)
{
int pervremainder = divisor;
divisor = dividend % divisor;
dividend = pervremainder;
}
return dividend;
}
或者,您也可以查看此Calculate GCD