美文网首页算法程序员首页投稿(暂停使用,暂停投稿)
【分享】一些经典的C/C++语言基础算法及代码(四)

【分享】一些经典的C/C++语言基础算法及代码(四)

作者: Orient_ZY | 来源:发表于2016-05-06 17:56 被阅读331次

    阅读到的一些经典C/C++语言算法及代码。在此分享。

    今天碰到的一个问题:用递归的方式颠倒字符串。

    C源代码如下

    #include <stdio.h>
    
    void Reverse();
    int main()
    {
        printf("Enter a sentence: \n");
        Reverse();
        return 0;
    }
    void Reverse()
    {
        char c;
        scanf("%c", &c);
        if( c != '\n')
        {
            Reverse();
            printf("%c", c);
        }
    }
    

    直接翻译为C++

    //最后却没有输出,不知道是哪里出问题了,可有高手赐教?
    #include <iostream>
    using namespace std;
    
    void Reverse();
    int main()
    {
        cout << "Enter a sentence: " << endl;
        Reverse();
        return 0;
    }
    void Reverse()
    {
        char c;
        cin >> c;
        if( c != '\n')
        {
            Reverse();
            cout << c;
        }
    }
    

    写成这样子就OK

    #include<iostream>
    using namespace std;
    
    void Reverse(char s[], int i)
    {
        if(s[i])
            Reverse(s,i+1);     //if条件成立,即进行递归
        cout << s[i];           //按反序输出字符串中的各个字符
    }
    int main()
    {
        char str[100];
        cout << "Enter a sentence: " << endl;
        cin.getline(str,100);
        Reverse(str,0);
        cout << endl;
    }
    

    相关文章

      网友评论

      本文标题:【分享】一些经典的C/C++语言基础算法及代码(四)

      本文链接:https://www.haomeiwen.com/subject/wqyjrttx.html