《C++从入门到精通》
《C++从入门到精通》学习笔记
同步于:黑凤梨の博客

随书资料
扫码自取

知识学习
习题实战
6.6.2蜗牛爬井
题目:
有一口井深10m,一只蜗牛从井底向井口爬,白天向上爬2m,晚上向下滑1m,问多少天可以爬到井口?
分析:
白天爬完2m时增加判断条件,到达10m直接输出所耗天数
代码实现:
#include
using namespace std;#define J 10int Day()
{for (int i = 0,j = 1;;j++){i = i + 2;if (i >= J) return j;i = i - 1;}
}int main()
{int n =Day();cout << "第" << n << "天爬到井口" << endl;system("pause");return 0;
}

7.8.1模拟生兔子
题目:
设一对大兔子每月生一对小兔子,每对新生兔在出生一个月后又下崽,假若兔子都不死亡。问:一对兔子一年能繁殖成多少对兔子?
分析:
第一个月:两只大兔子 2
第二个月:两只大兔子+两只小兔子 4
第三个月:四只大兔子+两只小兔子 6
第四个月:六只大兔子+四只小兔子 10
…
由此可得:第n月兔子数为=第n-1月兔子数量+第n-2月兔子数量
代码实现:
#include
using namespace std;int num = 2;int month = 0;
int func(int n)
{if (n == 1) return 2;if (n == 2) return 4;num = func(n - 1) + func(n - 2);return num;
}int main()
{cout << "请输入月份:";cin >> month;func(month);cout << "第" << month << "月的兔子数量为:" << num / 2 << endl;system("pause");return 0;
}

8.02 二维数组行列交换
#include
using namespace std;int fun(int array[3][3])
{int i, j, t;for (i = 0;i < 3;i++){for (j = 0;j < i;j++){t = array[i][j];array[i][j] = array[j][i];array[j][i] = t;}}return 0;
}void PrintArray(int array[3][3])
{int i, j;for (i = 0;i < 3;i++){for (j = 0;j < 3;j++){cout << "\t" << array[i][j];}cout << endl;}
}int main()
{int array[3][3] ={{1,2,3},{4,5,6},{7,8,9}};cout << "之前数组为:" << endl;PrintArray(array);fun(array);cout << "之后数组为:" << endl;PrintArray(array);system("pause");return 0;
}

8.5.1 打印“心”形图案
#include
using namespace std;
int main()
{int a[7][7] = {{0,0,0,0,0,0,0},{0,0,1,0,1,0,0},{0,1,0,1,0,1,0},{0,1,0,0,0,1,0},{0,0,1,0,1,0,0},{0,0,0,1,0,0,0},{0,0,0,0,0,0,0}};cout << " 韩宝建 " << endl;for (int i = 0;i < 7;i++)//Z{for (int j = 0;j < 7;j++){if (a[i][j] == 1){cout << "**";}else{cout << " ";}}cout << endl;}cout << " 赵二狗 " << endl;cout << endl;system("pause");return 0;
}

8.5.2 判断密码是否为6位
#include
using namespace std;int getlen(char strm[100])
{return strlen(strm);
}int main()
{char strm[100];int len = 0;while (1){cout << "请输入一个6位密码:" << endl;cin >> strm;len=getlen(strm);if (len == 6){cout << "密码正确!" << endl;break;}else{cout << "密码必须是6位! ";}}system("pause");return 0;
}

本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
