-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
#1. 简答
1.1
递归式,终止条件。
相关链接 http://blog.csdn.net/feixiaoxing/article/details/6838773 (该链接中将“堆栈”理解成“栈”)
1.2
理解课中所说的即可。
#2.
2.1.1 数列 (5分)
#include <stdio.h>
int main() {
int n[200] = {};
n[1] = 1;
n[2] = 1;
// 你的代码
for(int i = 3; i <= 20; i++) {
n[i] = n[i-1]+n[i-2];
}
printf("%d\n", n[i]);
return 0;
}
2.1.2 单词计数 (6分)
给定一个句子(假设该句子中不含有标点,即单词仅由空格分开),求出该句子含有多少个单词?
#include <stdio.h> #define TRUE 1 #define FALSE 0 int main() { // 申请1024长度的空间 int size = 1024; char* buff = (char*)malloc(size); int words_count = 0; // 单词个数 while(NULL != gets(buff)){ // buff为读取到的字符串,例如*buff = "I am a super man" int i; int isNewWord = TRUE; for(i = 0; buff[i] != '\0'; i++) { if(' ' == buff[i]) { words_count++; isNewWord = TRUE; } else { isNewWord = FALSE; } } if(buff[i-1] != ' ') { words_count++; } } printf("%d\n", words_count); // 释放空间 free(buff); return 0; }可直接运行的程序
#include <stdio.h> #define TRUE 1 #define FALSE 0 int main() { char *buff = "I am a super man"; int word = 0; int isNewWord = TRUE; int i; for(i = 0; buff[i] != '\0'; i++) { if(' ' == buff[i]) { word++; isNewWord = TRUE; } else { isNewWord = FALSE; } } if(buff[i-1] != ' ') { word++; } printf("%d\n", word); return 0; }
2.2 函数为什么要存在 (7分,6分,7分)
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int get_sum(int *number, int len) {
int retval = 0;
for(int i = 0; i < len; i++) {
retval += number[i];
}
return retval;
}
int get_sum2(int n) {
// 采用递归
return 1 == n ? 1 : get_sum2(n-1)+n;
}
int main() {
int *a, *b;
int numbers[] = {1,2,3,4,5};
swap(a, b);
/* sizeof()函数返回参数所占内存大小,sizeof(numbers)=20, sizeof(int)=4,所以sizeof(number)/sizeof(int)=5,这样就得到了numbers数组的长度
*/
int ans1 = get_sum(numbers, sizeof(numbers)/sizeof(int));
int ans2 = get_sum2(10);
printf("%d %d\n", ans1, ans2);
return 0;
}
2.3 指针如此有用 (7分)
int withdraw(int *balance, int cash) { // balance为余额,cash为当前取的额度
if(*balance >= cash) {
*balance -= cash;
return 0;
}
else {
return -1;
}
}
2.4 如此危险 (10分,10分)
(1) 输入一连串的a。因为变量在地址空间连续,而scanf输入的时候并不会做长度检查,所以超过yourname, yourpwd的字符你会沿着栈空间的增长方向覆盖,即将rootname, rootpwd的字符覆盖。从而修改了内存中密码用户名,从而登陆。
(2) 长度检查。
char yourname[8] = "";
if(len(yourname) > 8) return FAIL;