白日放歌须纵酒,青春作伴好还乡。

数组 题目

1.2034:【例5.1】反序输出

【题目描述】
输入n
个数,要求程序按输入时的逆序把这n
个数打印出来,已知整数不超过100
个。也就是说,按输入相反顺序打印这n
个数。

【输入】
输入一行共有n
个数,每个数之间用空格隔开。

【输出】
如题要求:一行,共有n
个数,每个数之间用一个空格隔开。

【输入样例】
1 7 3 4 5
【输出样例】
5 4 3 7 1

这道题的难点在于什么时候停止输入,用scanf();
拓展:
scanf()用法:

int a;
while(scanf("%d",&a)==1)
{

}

#include<iostream>
using namespace std;
int main()
{
	int a[100],b,n=0;
	while(scanf("%d",&b)==1)
	{
		a[n++]=b;
	}
	for(int i=n-1;i>=0;i--)
	{
		cout<<a[i]<<" ";
	}
	return 0;
}

2.2035:【例5.2】平移数据

这道题当初把我坑惨了……

【题目描述】
将a
数组中第一个元素移到数组末尾,其余数据依次往前平移一个位置。

【输入】
第一行为数组a
的元素个数;

第二行为n
个小于1000
的正整数。

【输出】
平移后的数组元素,每个数用一个空格隔开。

【输入样例】
10
1 2 3 4 5 6 7 8 9 10
【输出样例】
2 3 4 5 6 7 8 9 10 1

这道题用到了备份以及什么域,反正不重要

#include<iostream>
using namespace std;
int main()
{
	int n,bf;
	cin>>n;
	int a[n];
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	bf=a[0];
	for(int i=1;i<n;i++)
	{
		a[i-1]=a[i];
	}
	a[n-1]=bf;
	for(int i=0;i<n;i++)
	{
		cout<<a[i]<<" ";
	}
	
	return 0;
}

2037:【例5.4】约瑟夫问题

【题目描述】
N
个人围成一圈,从第一个人开始报数,数到M
的人出圈;再由下一个人开始报数,数到M
的人出圈;…输出依次出圈的人的编号。

【输入】
输入N
和M
。

【输出】
输出一行,依次出圈的人的编号。

【输入样例】
8 5
【输出样例】
5 2 8 7 1 4 6 3
【提示】
【数据范围】

对于所有数据,2≤N,M≤1000
。
#include<iostream>
using namespace std;
int main()
{
	int n,m;
	cin>>n>>m;
	bool a[n+1];
	for(int i=1;i<=n;i++)
	{
		a[i]=false;
	}
	int s=0,t=0,f=0;
	do
	{
		t++;
		if(t==n+1)
			t=1;
		if(a[t]==false)
			s++;
		if(s==m)
		{
			cout<<t<<" ";
			a[t]=true;
			s=0;
			f++;
		}
		
	}while(f!=n);
	return 0;
}

2038:【例5.5】最大数位置

【题目描述】
输入n
个整数,存放在数组a[1]
至a[n]
中,输出最大数所在位置(n≤1000
)。

【输入】
第一行,数的个数n
;

第二行,n
个正整数,每个数在232−1
之内。

【输出】
最大数所在位置。

【输入样例】
5
67 43 90 78 32
【输出样例】
3
#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n, a[1005], mxi = 1;
	cin >> n;
	for(int i = 1; i <= n; ++i)
		cin >> a[i];
	for(int i = 1; i <= n; ++i)
	{
		if(a[i] > a[mxi])
			mxi = i;
	}
	cout << mxi;
	return 0;
}
posted @ 2024-03-23 12:47  黄晟Dog  阅读(174)  评论(0)    收藏  举报
Live2D