1

これは学校の仕事です。与えられたintを文字列に変換する再帰関数を書くことになっています。私は近くにいることはわかっていますが、コードに欠けているものを指摘することはできません。ヒントは大歓迎です。

void intToStr(unsigned int num, char s[])
{
    if (num < 10)
    {   
        s[0] = '0' + num;
    }

    else
    {
        intToStr(num/10, s);
        s[strlen(s)] = '0' + num%10;
    }
}

編集:私の問題は、関数が事前に初期化された配列に対してのみ機能することですが、関数を初期化されていない関数で機能させると機能しません。

4

2 に答える 2

3

配列がゼロで初期化されていない限り、配列を変更するときにnullターミネータを追加するのを忘れています。

最後の文字の直後に追加するだけです。

void intToStr(unsigned int num, char s[])
{
    if (num < 10)
    {   
        s[0] = '0' + num;
        s[1] = 0;
    }

    else
    {
        intToStr(num/10, s);
        s[strlen(s)+1] = 0; //you have to do this operation here, before you overwrite the null terminator
        s[strlen(s)] = '0' + num%10;
    }
}

また、関数はsにすべての桁を保持するのに十分なスペースがあることを前提としているため、確実に保持することをお勧めします(INT_MAXは10桁の長さなので、少なくとも11文字が必要です)。

于 2012-12-22T00:04:17.700 に答える
0

Andrei Titaは、NULLターミネータで発生した問題をすでに示しています。別の方法を紹介しますので、さまざまなアプローチを比較対照できます。

int intToStr(unsigned int num, char *s)
{   
    // We use this index to keep track of where, in the buffer, we
    // need to output the current character. By default, we write
    // at the first character.
    int idx = 0;

    // If the number we're printing is larger than 10 we recurse
    // and use the returned index when we continue.
    if(num > 9)
        idx = intToStr(num / 10, s);

    // Write our digit at the right position, and increment the
    // position by one. 
    s[idx++] = '0' + (num %10);

    // Write a terminating NULL character at the current position
    // to ensure the string is always NULL-terminated.
    s[idx] = 0;

    // And return the current position in the string to whomever
    // called us.
    return idx;
}

私の代替案は、バッファに出力する文字列の最終的な長さも返すことに気付くでしょう。

今後のコースワークで頑張ってください!

于 2012-12-22T00:34:07.343 に答える