实验六指针的应用64 下载本文

内容发布更新时间 : 2024/5/16 4:01:19星期一 下面是文章的全部内容请认真阅读。

一、在以下程序中,主函数main调用了3个函数swap1、swap2和swap3,还定义了变量a和b,程序设计的目的是要求通过函数调用,交换main中变量a和b的值。请分析在swap1、swap2和swap3这3个函数中,哪个函数可以实现这样的功能。 分别使用变量和指针作为函数参数的示例程序 # include void main () {

int a = 1, b = 2;

int *pa = &a, *pb = &b;

void swap1(int x, int y), swap2( int *px, int *py ), swap3 (int *px, int *py);

swap1 (a, b); /* 使用变量a,b调用函数swap1() */ printf (\

a = 1; b = 2;

swap2(pa, pb); /* 使用指针pa,pb调用函数swap2()*/ printf (\

a = 1; b = 2;

swap3(pa, pb); /* 使用指针pa,pb调用swap3() */ printf (\ }

void swap1 (int x, int y) {

int t;

t= x; x = y; y = t; }

void swap2 (int *px, int *py) {

int t;

t = *px; *px = *py; *py = t; }

void swap3 (int *px, int *py) {

int *pt;

pt =px; px = py; py = pt; } 二、输入年份和天数,输出对应的年、月、日。要求定义和调用函数month_day ( year, yeardy, *pmonth, *pday),其中year是年,yearday是天数,*pmonth和*pday是计算得出的月和日。例如,输入2000和61,输出2000-3-1,即2000年的第61天是3月1日。 # include void main () {

int day, month, year, yearday; /* 定义代表日、月、年和天数的变量*/ void month_day(int year,int yearday, int *pmonth,int *pday);/*声明计算月、日的函数*/

printf(\ /* 提示输入数据:年和天数 */ scanf (\

month_day (year, yearday, &month, &day ); /* 调用计算月、日函数 */ printf (\ }

void month_day ( int year, int yearday, int * pmonth, int * pday) {

int k, leap;

int tab [2][13]= {

{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, }; /* 定义数组存放非闰年和闰年每个月的天数 */

leap=year%4==0 && year% 100!= 0 || year@0==0; /* 建立闰年判别条件leap */

/* 如果leap=1,表示为闰年,从tab[1][k]中取k月的天数;否则为非闰年 */

请将程序补充完整 }

三、输入n个正整数,将它们从小到大排序后输出。要求使用冒泡排序算法。

/* 指针和数组及存储单元 - 冒泡排序算法 */ #include

void swap2 (int *, int *); void bubble (int a[], int n);

void main() {

int n, a[8]; int i;

printf(\ scanf(\

printf(\ for (i=0; i

scanf(\ bubble(a,n);

printf(\ for (i=0; i

printf(\

return 0; }

void bubble (int a[], int n) /* n是数组a中待排序元素的数量 */ {

请补充完整程序 }

void swap2 (int *px, int *py) {

请补充完整程序,功能是交换 }

四、输入两个字符串,要求将这两个字符串交叉连接。如串string1为\,串string2为\,则合并后的串为\。