私は代入に取り組んでいますが、それを繰り返すために私のメソッドオーバーロードに悩まされていますmain
で指定された回数がnth
倍です。私はというループの最後のメソッドをdo while
ループでラップしていますが、オーバーロードされているメインメソッドで指定されているループ回数xを実行する必要があるため正しく動作していないようです。私が理解できないのはそれだけです。相続人は私のMain
です:C#でメソッドをオーバーロードする
static void Main(string[] args)
{
Collatz thisCollatz = new Collatz(15);
Console.WriteLine(
string.Format("Collatz iteration is {0} and value is {1}",
thisCollatz.Iteration, thisCollatz.CurrentVal));
thisCollatz.Iterate();
Console.WriteLine(
string.Format("Collatz iteration is {0} and value is {1}",
thisCollatz.Iteration, thisCollatz.CurrentVal));
//// Overload of iterate method
thisCollatz.Iterate(10);
Console.WriteLine(
string.Format("Collatz iteration is {0} and value is {1}",
thisCollatz.Iteration, thisCollatz.CurrentVal));
Console.WriteLine("\nPAK..." + "\nProduced By: Jeremy Garcia");
Console.ReadKey();
}
、ここでは、私は私のクラスに持っているものです。
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);
}
}
は、事前に協力いただきありがとうございます。私はプログラム全体を書き直すつもりはなく、最後に働く方法を得るだけです。再度、感謝します。
「動作していないようです」は曖昧です。右下のポストのゴブス**関連** – Plutonix
「機能していないように思われる」という意味に展開してください。あなたの画面は見えません。エラーが出ていますか?期待される行動は何ですか?それは実際に何をしていますか? **具体的にする** – Amy
「do-while」は永遠に実行されていますか? - これは、そうであると思われるものです。ループは反復が0になることはないが、ループを維持するように設計されています。あなたのコードに何もあなたの反復をゼロに設定することはありません - したがって、無限ループです。ループ内のどこかで反復回数をカウントするか、ゼロに設定する必要があり、ループを終了させることができます。 – Darren