我正在尝试使用C#片段中的用户输入实现欧几里德算法,作为我学习该语言过程的一部分.MVS告诉我if和elif语句以及这些语句的结束括号都有错误.现在,来自pythonic背景这对我来说似乎很自然,所以请帮助我找出可能的错误.非常感谢帮助.
码:
namespace EuclideanAlgorithm
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two numbers to calculate their GCD");
int input1 = Convert.ToInt32(Console.ReadLine());
int input2 = Convert.ToInt32(Console.ReadLine());
int remainder;
int a;
int b;
if (input1 == input2);
{
Console.Write("The GCD of", input1, "and", input2, "is", input1);
Console.ReadLine();
}
else if (input1 > input2);
{
a = input1;
b = input2;
while (remainder != 0);
{
remainder = a % b;
a = b;
b = remainder;
}
Console.Write("The GCD of", input1, "and", input2, "is", b);
Console.ReadLine();
}
else if (input1 < input2);
{
a = input2;
b = input1;
while (remainder != 0);
{
remainder = a % b;
a = b;
b = remainder;
}
Console.WriteLine("The GCD of", input1, "and", input2, "is", b);
Console.ReadLine();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
那么你需要删除ifs 上的分号.所以:
if (input1 == input2);
Run Code Online (Sandbox Code Playgroud)
变为:
if (input1 == input2)
Run Code Online (Sandbox Code Playgroud)
这也适用于else if和while.另外只是旁注:
Console.Write("The GCD of", input1, "and", input2, "is", input1);
Run Code Online (Sandbox Code Playgroud)
这将产生:
GCD
如果你想做一个,string.Format你需要这样做:
Console.Write("The GCD of {0} and {1} is {2}", input1, input2, input1);
Run Code Online (Sandbox Code Playgroud)
这里有更多信息string.Format
还有一件事 - 确保在你设置它的地方初始化你的余数,否则你将无法编译本地变量的余数可能在访问之前没有被初始化:
int remainder = 0;
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助.
编辑
如果你希望你的余数在第一次评估时不是0,你可以使用do/while循环:
do
{
remainder = a % b;
a = b;
b = remainder;
} while (remainder != 0);
Run Code Online (Sandbox Code Playgroud)