我已经被赋予了重写一个使用goto语句的程序的任务,其唯一目的是为了证明它们是多么令人沮丧,而且我已经知道它们确实非常令人沮丧。翻阅调试器几个小时后,我仍然遇到问题,有没有人能为我伪代码,我可能会更好地理解它?除了为每个goto创建if和else语句之外我都迷失了。
namespace Assignment_03_Nasty_Code
{
class Assignment03
{
static void Main(string[] args)
{
Console.WriteLine("Assignment 03 = " + new Assignment03().Solve());
}
public int Solve()
{
int result = 0;
int upperSearchLimit = 1_000_000;
Console.WriteLine("Building list of primes...");
ArrayList primes = Utils.BuildListOfPrimes(upperSearchLimit);
Console.WriteLine(" Done.");
// Step through the odd composite numbers
for (int i = 19; i < upperSearchLimit; i+= 2)
{
Label02:
if (primes.Contains(i))
goto Label03;
// Is the number divisible by a prime?
int j = 0;
Boolean match = false;
Label01:
int tmp;
int prime = (int)primes[j];
tmp = i - prime;
int half = tmp /= 2;
int squareRoot = (int) Math.Sqrt(half);
if (tmp != squareRoot * squareRoot)
goto Label04;
// We got one
//System.out.println(i + " is a composite that can be written as the sum of a prime and twice a square");
match = true;
Console.WriteLine(i + " = " + (int)primes[j] + " + 2 * " + half );
Label04: // Second goto
j++;
if ((int)primes[j] < i)
goto Label01;
if (match == false)
{
Console.WriteLine("No match for " + i);
result = i;
break;
}
//goto Label02;
Label03: // First goto
int x;
}
return result;
}
}
}
答案 0 :(得分:0)
我已在您的代码中替换了goto
以及该结果
public int Solve()
{
var result = 0;
var upperSearchLimit = 1_000_000;
Console.WriteLine("Building list of primes...");
ArrayList primes = Utils.BuildListOfPrimes(upperSearchLimit);
Console.WriteLine(" Done.");
for (var i = 19; i < upperSearchLimit; i += 2)
{
if (primes.Contains(i))
{
continue;
}
var j = 0;
var match = false;
do
{
int tmp;
var prime = (int)primes[j];
tmp = i - prime;
var half = tmp /= 2;
var squareRoot = (int)Math.Sqrt(half);
if (tmp == squareRoot * squareRoot)
{
match = true;
Console.WriteLine(i + " = " + (int)primes[j] + " + 2 * " + half);
}
j++;
} while ((int)primes[j] < i);
if (match == false)
{
Console.WriteLine("No match for " + i);
result = i;
break;
}
}
return result;
}