本博客内容为中国大学生MOOC国家精品课程《计算机程序设计C++》作业记录,仅供参考,观者忌照搬照抄,欢迎交流批评指正!
(注:由于本人学习时,前八周的作业提交时间已过,因此这八周的作业代码只在自己的编译器上测试运行通过,在课程网站上还未测试,于下学期开课时,再另行测试,如您发现有明显错误,可留言评论)
##第7周编程作业
本周作业为指针的应用
- 编写函数重置两个变量的值
#include<iostream>
using namespace std;
void reset(int *a,int *b)
{
int avg;
avg = (*a + *b) / 2.0+0.5 ;
*a = avg;
*b = avg;
return;
}
int main()
{
int a, b;
cin >> a >> b;
reset(&a, &b);
cout << a << ' ' << b;
return 0;
}
- 编写函数对数组中的元素求和
#include<iostream>
using namespace std;
void add_array(int a, int *sum)
{
*sum += a;
return;
}
int main()
{
int a[100],n,i,sum=0;
for (n = 0; n < 100; n++)
{
cin >> a[n];
if (a[n] == -1)break;
}
for (i = 0; i < n; i++)
{
add_array(a[i], &sum);
}
cout << sum;
return 0;
}
- 数组清零
#include<iostream>
using namespace std;
void clear(int *a, int n)
{
for (int i = 0; i < n; i++)
{
a[i] = 0;
}
return;
}
int main()
{
int a[100], n, i,count;
for (n = 0; n < 100; n++)
{
cin >> a[n];
if (a[n] == -1)break;
}
cin >> count;
clear(a, count);
for (i = 0; i < n-1; i++)
{
cout << a[i] << ' ';
}
cout << a[i];
return 0;
}
- 使用函数指针切换加密方法
#include<iostream>
using namespace std;
const char low[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z','a','b','c' };
const char upp[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C' };
void caesar(char s[])
{
int i = 0, num;
while (s[i] != '\0')
{
if (s[i] >= 'a' && s[i] <= 'z')
{
num = s[i] - 'a';
num += 3;
s[i] = upp[num];
}
else if (s[i] >= 'A' && s[i] <= 'Z')
{
num = s[i] - 'A';
num += 3;
s[i] = low[num];
}
i++;
}
}
void oddeven(char s[])
{
int i = 0, n=0;
while (s[i] != '\0')
{
i++;
n++;
}
int n1 = n / 2.0 + 0.5;//存放奇数位的数组长度
int n2 = n - n1;//存放偶数位的数组长度
char *a = new char[n1];
char *b = new char[n2];
for (i = 0; i < n1; i++)
{
a[i] = s[2 * i];
}
for (i = 0; i < n2; i++)
{
b[i] = s[2 * i + 1];
}
for (i = 0; i < n1; i++)
{
s[i] = a[i];
}
for (i = n1; i < n; i++)
{
s[i] = b[i-n1];
}
delete[]a;
delete[]b;
return;
}
void cipher(void (*f)(char s[]), char s[])//该函数的两个参数,一个是指向函数的指针,一个是计算的字符串
//其中函数指针 void(*f)(char s[]) 是指向一个返回类型为void 变量为char s[]的函数
{
(*f)(s);//通过函数指针调用函数
return;
}
int main()
{
char a[100];
int n;
cin >> a;
cin >> n;
void (*f)(char s[]);//定义一个函数指针
if (n == 1)f = caesar;//f指向凯撒加密
if (n == 2)f = oddeven;//f指向单双号加密
cipher(f, a);
cout << a;
return 0;
}
- 编写求函数区间平均值的通用函数
#include<iostream>
#include<cmath>
using namespace std;
int a, b, c;//函数系数设为全局变量
int m;
int func1(int x)
{
return a*x*x + b*x + c;
}
int func2(int x)
{
return int(pow(x, m));
}
int avg(int(*fun)(int n), int n1,int n2)
{
int avg = 0;
for (int i = n1; i <= n2; i++)
avg += ((*fun)(i));
avg /= (n2 - n1+1);
return avg;
}
int main()
{
cin >> a >> b >> c >> m;
int n1, n2;
cin >> n1 >> n2;
int(*f)(int);
f = func1;
cout << avg(f, n1, n2)<<endl;
f = func2;
cout << avg(f, n1, n2)<<endl;
return 0;
}
以上为第7周的编程作业。