本博客内容为中国大学生MOOC国家精品课程《计算机程序设计C++》作业记录,仅供参考,观者忌照搬照抄,欢迎交流批评指正!
(注:由于本人学习时,前八周的作业提交时间已过,因此这八周的作业代码只在自己的编译器上测试运行通过,在课程网站上还未测试,于下学期开课时,再另行测试,如您发现有明显错误,可留言评论)
##第5周编程作业
本周作业内容为函数的建立与调用
- 编写字符串反转函数mystrrev
#include<iostream>
using namespace std;
void mystrrev(char str[])
{
int i = 0,n=0;
while (1)
{
if (str[i] == '\0')break;
n++;
i++;
}
char temp;
for (i = 0; i < n/2; i++)
{
temp = str[i];
str[i] = str[n - 1 - i];
str[n - 1 - i] = temp;
}
}
int main()
{
char a[100];
cin.getline(a, 100);
mystrrev(a);
cout << a;
return 0;
}
- 编写一组求数组中最大最小元素的函数
#include<iostream>
using namespace std;
int imax(int array[], int count)
{
int max = array[0];
for (int i = 0; i < count; i++)
{
max = (max > array[i]) ? max : array[i];
}
return max;
}
int imin(int array[], int count)
{
int min = array[0];
for (int i = 0; i < count; i++)
{
min = (min < array[i]) ? min : array[i];
}
return min;
}
int main()
{
int a[100];
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
cout << imax(a, n) << endl;
cout << imin(a, n) << endl;
return 0;
}
- 编写函数判断一个整数是否为素数
#include<iostream>
using namespace std;
int isprime(int a)
{
if (a <= 1) return 0;
for (int i = 2; i < a; i++)
{
if (a%i == 0) return 0;
}
return 1;
}
int main()
{
int in = -1, num[100],n=0;
while (in != 0)
{
cin >> in;
if (isprime(in) == 1)
{
num[n] = in;
n++;
}
}
int i = 0;
for ( i = 0; i < n-1; i++)
{
cout << num[i] << ' ';
}
cout << num[i];
return 0;
}
- 编写函数去除字符串中包含的非字母字符(不包括空格),并将小写字母转换成大写字母
#include<iostream>
using namespace std;
void Remove(char a[])
{
int i = 0;
while (a[i] != '\0')
{
if (a[i] >= 'a'&&a[i] <= 'z')
{
a[i] += 'A' - 'a';
}
else if ((a[i] >= 'A'&&a[i] <= 'Z') || a[i] == ' ')
{
a[i] = a[i];
}
else
{
int j = i;
while (1)//后面的元素往前移动
{
a[j] = a[j + 1];
j++;
if (a[j] == '\0')break;
}
i--;
}
i++;
}
}
int main()
{
char a[200];
cin.getline(a,200);
Remove(a);
cout << a;
return 0;
}
- 编写函数计算一个英文句子中的单词个数
#include<iostream>
using namespace std;
bool judgeLetter(char a)
{
if ((a >= 'a'&&a <= 'z') || (a >= 'A'&&a <= 'Z'))
return true;
else
return false;
}
bool judgePunctuation(char a)
{
if (a == ',' || a == '.' || a == '?' || a == '!' || a == ':' || a == ';' || a == '\"' || a == '\'')
return true;
else
return false;
}
int count(char a[])
{
int c= 0,i=1;//c是计算的单词数,i是下标
while (a[i] != '\0')
{
if (a[i] == ' '&&judgeLetter(a[i-1]))c++;//如果一个字符是空格且前面是字母,单词数加一
if (judgePunctuation(a[i]) && judgeLetter(a[i - 1]))c++;//如果一个字符是标点符号前面是字母,单词数加一
i++;
}
if (judgeLetter(a[i - 1]))c++;//如果最后没有以标点符号结尾而是以单词结尾,单词数加一
return c;
}
int main()
{
char a[200];
cin.getline(a,200);
cout << count(a);
return 0;
}
以上为第5周编程作业。