用指针处理的一道题

题目:有n个整数,使前面各数顺序向后移m个位置,最后m个数变成前面m个数,

如:

1 2 3 4 5 6 7 8 9

n=9,m=3时

移动后是:

7 8 9 1 2 3 4 5 6

编写一个程序完成以上过程。

思路:每当移动一个数,如当移动一次,将最后一个数移动到最前面,倒数第二个数变成最后一个数,依次类推,直到所有的数移动完毕。

移动所有数的过程和移动一个数的过程一样,所以可以用递归解决。


#include<stdio.h>
void input(int *a,int n)
{
	int i;
	for(i=0;i<n;i++)
	{
		scanf("%d",a++);
	}
}
void ouput(int *a,int n)
{
	int i;
	for(i=0;i<n;i++)
	{
		printf("%d ",*a++);
	}
} 
void move(int a[],int n,int m)
{
	int *p,a_end;
	a_end=*(a+n-1);
	for(p=a+n-1;p>a;p--)
	{
		*p=*(p-1);
	}
	*a=a_end;
	m--;
	if(m>0) move(a,n,m);
}
int main()
{
	int n,m;
	int a[100];
	scanf("%d%d",&n,&m);
	input(a,n);
	//sort(a,n,m);
	move(a,n,m);
	ouput(a,n);
	return 0;
}



题目:定义一个结构体代表学生的信息,包含姓名、年龄、分数三个字段,然后编写一个程序,使用结构体指针操作这个学生信息。 ### 题目描述: 假设我们需要设计一个程序来管理学生的成绩数据,包括学生的姓名、年龄以及数学、语文两门科目的成绩。请完成以下任务: #### 步骤 1:定义结构体类型 定义一个名为 `StudentInfo` 的结构体类型,它应该包含以下几个成员变量: - `name`: 学生的姓名。 - `age`: 学生的年龄。 - 数学成绩 `mathScore` 和语文成绩 `chineseScore`。 #### 步骤 2:创建函数来设置和获取学生信息 编写两个函数 `setScores` 和 `getScores` 来处理学生信息的设定和读取,分别为: - `void setScores(StudentInfo *info, int mathScore, int chineseScore)` : 设置学生数学成绩和语文成绩。 - `int getMathScore(const StudentInfo *info)` 和 `int getChineseScore(const StudentInfo *info)`: 分别获取学生的数学成绩和语文成绩。 #### 步骤 3:主函数中的应用 在主函数中,创建一个 `StudentInfo` 结构体的指针实例,使用之前定义的函数来设置该学生的成绩,最后输出学生的详细信息以验证设置是否成功。 #### 示例代码: ```cpp #include <iostream> using namespace std; // 定义结构体类型 struct StudentInfo { string name; int age; int mathScore; int chineseScore; }; // 函数声明 void setScores(StudentInfo *info, int mathScore, int chineseScore); int getMathScore(const StudentInfo *info); int getChineseScore(const StudentInfo *info); int main() { // 创建结构体指针实例 StudentInfo* student = new StudentInfo(); // 使用函数设置学生信息 setScores(student, 90, 85); // 输出学生信息 cout << "Name: " << student->name << endl; cout << "Age: " << student->age << endl; cout << "Math Score: " << getMathScore(student) << endl; cout << "Chinese Score: " << getChineseScore(student) << endl; delete student; // 释放内存 return 0; } // 实现函数 void setScores(StudentInfo *info, int mathScore, int chineseScore) { info->mathScore = mathScore; info->chineseScore = chineseScore; } int getMathScore(const StudentInfo *info) { return info->mathScore; } int getChineseScore(const StudentInfo *info) { return info->chineseScore; } ``` ### 相关问: 1. 在C++中如何定义和使用结构体指针? 2. 举例说明如何使用结构体指针进行数据的设置和获取。 3. 在上述程序中,如何保证安全性地分配和释放动态内存? --- 请注意,在实际的项目中应考虑内存安全性和资源管理。以上示例展示了基本的结构体指针使用流程。在大型项目中,通常还会涉及到更复杂的错误检查、异常处理、资源回收策略等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值