C# 在C中重载一个方法
我正在做一项作业,我被困在重载上,我的方法重复了主菜单中指定的第n次。我将类中最后一个名为Collatz的方法包装在do-while循环中,但它似乎工作不正常,因为它应该按照主方法中指定的次数运行循环x,在主方法中它被重载。这是我唯一搞不懂的部分。以下是我的主要观点: 这是我在班上学到的:C# 在C中重载一个方法,c#,methods,overloading,C#,Methods,Overloading,我正在做一项作业,我被困在重载上,我的方法重复了主菜单中指定的第n次。我将类中最后一个名为Collatz的方法包装在do-while循环中,但它似乎工作不正常,因为它应该按照主方法中指定的次数运行循环x,在主方法中它被重载。这是我唯一搞不懂的部分。以下是我的主要观点: 这是我在班上学到的: class Collatz { // _Iteration is how many iterations of Collatz have run since initializatio
class Collatz
{
// _Iteration is how many iterations of Collatz have run since initialization
// _CurrentVal is the current value of the Collatz process
private int _Iteration;
private int _CurrentVal;
public Collatz(int InitialValue)
// initializer
{
CurrentVal = InitialValue;
Iteration = 0;
}
public int CurrentVal
// returns the current Collatz value or -- within the class -- allows it to be set
{
get { return _CurrentVal; }
private set
{
if (value > 0)
{
_CurrentVal = value;
}
else
{
throw new Exception("CurrentVal is not a positive integer");
}
}
}
public int Iteration
// returns the current number of Collatz iterations or
// -- within the class -- allows it to be set
{
get { return _Iteration; }
private set { _Iteration = value; }
}
public void Iterate()
// Executes one iteration of Collatz creating a
// new CurrentVal from the existing CurrentVal
{
if (_CurrentVal != 1)
{
if (_CurrentVal % 2 == 0)
{
_CurrentVal = _CurrentVal / 2;
_Iteration ++;
}
else if (_CurrentVal % 2 != 0)
{
_CurrentVal = (_CurrentVal * 3) + 1;
_Iteration ++;
}
else
{
_CurrentVal = 1;
_Iteration = 1;
}
}
}
public void Iterate(int iterations)
// Check if CurrentVal is (already) 1 -- don't calculate
// new CurrentVal nor increment Iteration if so
// Otherwise calculate new CurrentVal and increment Iteration
{
do
{
if (_CurrentVal != 1)
{
if (_CurrentVal % 2 == 0)
{
_CurrentVal = _CurrentVal / 2;
_Iteration++;
}
else if (_CurrentVal % 2 != 0)
{
_CurrentVal = (_CurrentVal * 3) + 1;
_Iteration++;
}
else
{
_CurrentVal = 1;
_Iteration = 1;
}
}
} while (iterations != 0);
}
}
提前谢谢你的帮助。我不想重写整个程序,只是简单地使用最后一个方法。再次感谢。您需要减少迭代计数器以避免无限循环。比如:
do
{
...
iterations--;
} while (iterations != 0);
完成工作后,您需要确保将迭代变量设置为0,以退出do/while循环。似乎不起作用,这是模糊的。在右侧的“相关”下有大量的帖子,请详细说明似乎不起作用的内容。我们看不到你的屏幕。你有错误吗?预期的行为是什么,它实际上在做什么?具体一点,当你永远奔跑时,你是否找到了你的目标这似乎是事实。您的循环设计为在迭代次数永远不等于零的情况下保持循环;代码中的任何内容都不会将迭代次数设置为零,因此这是一个无限循环。在您的内部某处,您需要向下计数迭代次数或将其设置为零,从而允许您的循环结束。您的最后一个方法Iterate接受一个参数iterations,该参数在10中传递。在该方法的主体中,如果该值不等于0,则while条件将等于true-由于迭代的值从未更改,因此看起来这将无限期地循环。它不会运行指定次数的代码,即在main中指定的迭代,设置为10Perfect!这是可行的,但它向我展示了11次迭代,而实际上它被设置为10次。我遗漏了什么吗?如果11次迭代指的是thisCollatz.Iteration的值为11,可能是因为您已经使用thisCollatz.Iterate将其设置为1;呼叫记住_迭代的值在对象内共享,并且每个操作都修改其现有值。
do
{
...
iterations--;
} while (iterations != 0);