其实就是讲函数。。也没啥好讲的
注意几个传递是重点: 值传递 指针传递 引用传递 。
其它的基本看过谭浩强C的都应该掌握的挺好的。。
几个习题 我也没刻意的写成函数。。 完全当成了字符串处理练习。。额。。老师 别打我。。。
不过有个地方还是要注意一下 Java学多了可能会无解。C++使用string声明对象 只要不是new或者malloc出来的 都是分配在栈中 而且是值传递 不存在引用类型。
void get(string s) {
cin >> s;
}
int main()
{
string s;
get(s);
cout << s << endl; //输出空串 return 0;
}1.编写字符串反转函数mystrrev,该函数的功能是将指定字符串中的字符顺序颠倒(前变后,后变前)。然后再编写主函数验证之。注意,输入输出应在主函数中进行。
/*此题我直接调用了reverse 实在没啥好写的。。就是个指针传递 好偷懒。。*/
#include "iostream"
#include "algorithm"
#include "cstring"
using namespace std;
int main() {
char s[101];
cin.getline(s, 100);
reverse(s,s+strlen(s));
cout << s << endl;
return 0;
}
2.不写了、、初学者写吧。。
3.编写函数int isprime(int a);用来判断整数a是否为素数,若是素数,函数返回1,否则返回0。调用该函数找出任意给定的n个整数中的素数。 注意,1不是素数。
#include "iostream"
#include "algorithm"
#include "cstring"
using namespace std;
bool isPrime(int n) {
if (n == 1)
return 0;
if (n == 2)
return 1;
if (n % 2 == 0)
return 0;
bool flag = 1;
for (int i = 3; i <= sqrt(n); i+=2) {
if (n%i == 0) {
flag = 0;
break;
}
}
return flag;
}
int main() {
int n;
int t = 1;
while (cin >> n) {
if (n == 0)
break;
if (isPrime(n)) {
if (t == 1)
cout << n;
else
cout << " " << n;
t++;
//cout << endl;
}
}
return 0;
}
4.
题目内容:
编写函数去除字符串中包含的非字母字符(不包括空格),并将小写字母转换成大写字母。
#include "iostream"
#include "algorithm"
#include "string"
using namespace std;
int main() {
string s;
getline(cin, s);
for (int i = 0; i<s.length(); ) {
if ((!isalpha(s[i])) && (s[i] != ' ')) {
s.erase(i,1);
}
else {
if (islower(s[i])) {
s[i] = toupper(s[i]);
}
i++;
}
}
cout << s << endl;
return 0;
}5.
题目内容:
编写函数计算一个英文字符串中的单词个数。
#include "iostream"
#include "cstdio"
#include "cstring"
#include "string"
#include "queue"
using namespace std;
int main()
{
char s[501];
cin.getline( s,501);
int cnt = 0;
char* p = strtok(s,",.? ");
while (p!=NULL) {
cnt++;
p = strtok(NULL, ",.? ");
}
cout << cnt << endl;
return 0;
}
299

被折叠的 条评论
为什么被折叠?



