3.22作业解答

 作业1: 设计一个函数:int  arraySum(int a[], int n),求一维数组a前n个数的和。现在利用int *p替换int a[]

作业2:设计一个函数: void swap(),根据用户输入的两个数num1和num2,利用指针实现变量值的交换。

#include <stdio.h>
void swap();
int arraySum(int a[], int n);
void main()
{
int nums[]={1,3,5,7,9};
int sum=arraySum(nums,4);
printf("和是%d\n",sum);
//swap();
}
void swap()
{
int num1,num2;

int *ptr_num1=&num1,*ptr_num2=&num2;
int ptr_nums=0;
printf("请输入num1的值\n");
scanf("%d",&num1);
printf("请输入num2的值\n");
scanf("%d",&num2);
printf("交换前num1的值是%d,num2的值是%d\n",num1,num2);
ptr_nums=*ptr_num1;
*ptr_num1=*ptr_num2;
*ptr_num2=ptr_nums;
printf("交换后num1的值是%d,num2的值是%d\n",*ptr_num1,*ptr_num2);

}
int arraySum(int a[], int n)
{
int *p;
int sum=0;
int i;
p=a;
for(i=0;i<n;i++,p++)
{
sum+=*p;
}
return sum;

}

posted on 2017-03-23 18:47  流逝之羽  阅读(82)  评论(0编辑  收藏  举报

导航