这种代码通常在PHP中工作,但是由于范围在C#中要严格得多,事实并非如此。我无法想出一种不重复自己的方式来编写这段代码。C#变量作用域和“switch”语句?
static double Cube()
{
Console.Write("Enter the side length of the cube: ");
try
{
double x = Convert.ToDouble(Console.Read());
return Math.Pow(x, 3);
}
catch (FormatException)
{
Console.WriteLine("Invalid input, please enter a number.");
Cube();
}
return 1;
}
..Later在main():
switch (choice)
{
case 0:
return;
case 1:
double final = Cube();
break;
default:
Console.WriteLine("Please enter 0 or 1.");
Main();
break;
}
Console.WriteLine("The volume is: {0}", Convert.ToString(final));
的Cube()
方法工作得很好,但它在我看来凌乱(return 1
末使编译器高兴)。但出现错误提示名称'final'在当前上下文中不存在。它无法找到最终的。因此,让我看到的这个工作的唯一方法是在double final = Cube()后面放置Console.WriteLine
语句。
我也试过在开关外面声明double final;
,然后在每种情况下只设置final
,但那也没有奏效。
谢谢!
“还没有工作”(与其他事情尝试)是错误的/误导。他们会1)工作或2)导致不同的错误。 – 2012-03-20 00:26:49
因为你对Cube的定义很混乱,你必须把'return 1'。它做了太多的事情,并且你在catch中使用递归也不是很干净。该函数必须返回一个值,所以你任意选择1作为失败返回。如果你不喜欢那样,移动Math.Pow并决定你在哪里可以真正得到正确的错误行为。 – CodexArcanum 2012-03-20 00:34:08