三、請撰寫一段程式執行以下工作,不限程式語言:

  輸入:字串

  輸出:原字串順序顛倒

解:

#include <iostream>
#include <cstdlib>
using namespace std;


int main()
{
    char *ptr;
    int l,k=0;
    
    cout<<"請輸入字串大小: ";
    cin>>l;
    ptr=new char[l];
    
    cout<<"請輸入字串: ";
    cin>>ptr;
    
    while(*ptr!='\0')
    {
        ptr++;
        k++;
    }
    
    cout<<"字串反轉: " ;    
    for(int i=k;i>=0;i--)
    {
             cout<<*(ptr--);
    }
    
    system("pause");
    return 0;
}

 

五、桌上有N本書成一疊,……。

輸入:一個初始書本序列和一個閱讀書之序列

輸出:最終的書本狀態

解:

#include <iostream>
#include <cstdlib>
#define N 5
using namespace std;
void read_book(int *a,int b)
{
    int stack[N],top=0,i=1;
    
    while(a[top]!=b)
    {
        stack[top]=a[top];
        top++; //下一個要放的位址
    }
    while(top>0)
    {
        top--;
        a[i++]=stack[top];
    }
    a[0]=b;
    
    cout<<"讀書本"<<b<<"之後的書本狀態"<<endl;
    for(int j=0;j<N;j++)
            cout<<"書本"<<a[j]<<endl;
}

int main()
{
    int book[N];
    int read[N];
    int i;
    
    cout<<"輸入一個初始書本序列: "<<endl;
    for(i=0;i<N;i++)
    {
            cout<<"第"<<i+1<<"本書: ";
            cin>>book[i];
            cout<<endl;
    }
    cout<<"初始書本序列: "<<endl;
    for(i=0;i<N;i++)
    {
        cout<<"書本"<<book[i]<<endl;
    }
    
    cout<<"輸入一個讀書序列: "<<endl;
    for(i=0;i<N;i++)
    {
            cout<<"第"<<i+1<<"本書: ";
            cin>>read[i];
            cout<<endl;
    }
    
    for(i=0;i<N;i++)
    {
        read_book(book,read[i]);
    }
     
    system("pause");
    return 0;
}

arrow
arrow
    全站熱搜

    Rinoa 發表在 痞客邦 留言(0) 人氣()