歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++經典題目:有n個整數,使前面各數順序向後移動m個位置

C++經典題目:有n個整數,使前面各數順序向後移動m個位置

日期:2017/3/1 9:52:48   编辑:Linux編程

問題描述:

有n個整數,使前面各數順序向後移動m個位置,最後m個數變成最前m個數。

程序代碼:

#include<iostream>
#define MAXLEN 200
using namespace std;
int a[MAXLEN],b[MAXLEN];
int main()
{
int * move(int a[],int n,int m); //聲明用來進行移動操作的函數
int *p;
int n=0,m=0,i=0; //i是計數器
cout<<"請輸入數字的個數:";
cin>>n;
cout<<"\n請輸入這些數字\n"<<endl;
//初始化數組
for(i=1;i<=n;i++)
{
cin>>a[i];
}
cout<<"\n請輸入要向後移動的位數m:";
cin>>m;
p=move(a,n,m); //執行移動操作
cout<<"\n移動後的數字序列為:\n"<<endl;
//輸出數組
for(i=1;i<=n;i++)
{
cout<<*(p+i)<<" ";
}
cout<<"\n\n";
return 0;
}
int * move(int a[],int n,int m)
{
int i=0,k;
for(i=n;i>0;i--)
{
k=(i+m)%n; //執行向後移動的操作
if(k==0)k=n; //當能夠整除的時候,說明(i+m)等於n
b[k]=a[i]; //將向後移動的數據存到數組b中
}
return b; //返回數組頭指針
}

程序運行界面:

Copyright © Linux教程網 All Rights Reserved