単一の再帰関数を使用して、長さが不明な整数の数字を正しい順序で出力する方法は??
int digit(int n)
{
if (n==0)
{
}
else
{
cout << n%10 << endl;
return digit(n/10);
}
}
//the above function prints it in reverse
単一の再帰関数を使用して、長さが不明な整数の数字を正しい順序で出力する方法は??
int digit(int n)
{
if (n==0)
{
}
else
{
cout << n%10 << endl;
return digit(n/10);
}
}
//the above function prints it in reverse
これは機能します。
[編集:コードは入力、つまり +ve、0、-ve 整数に対して機能します。-ve記号ではなく、数字のみを出力します]
void digit(int n) //no need to return a value
{
if (n < 0)
n = -1*n;
if (n/10 > 0) //no need have else blocks
{
//for the correct order, make the recursive call first
digit(n/10);
}
//print when you reach the most significant digit
cout << n%10 << endl;
}
1 回の関数呼び出しでどのステップを実行し、次の関数呼び出しに何を委譲するかを考える必要があります。1桁の印刷は良い候補のようです。最下位 (右端) の桁を取るのは非常に簡単です。整数を 10 で割った余りです。
最後に最下位桁を出力したいので、最初に関数に委任する必要があります。
digit( n / 10 );
std::cout << n % 10;