实验1 C++函数
来源:互联网 发布:淘宝数码相机 编辑:程序博客网 时间:2024/06/13 23:31
- 掌握定义函数的方法、函数实参与形参的对应关系以及“值传递”的方式。
- 熟悉函数的嵌套调用和递归调用的方法。
- 熟悉全局变量、局部变量概念和使用方式。
二.实验内容:
- 运行调试第2章编程示例2-5减法游戏;完成练习题2.5.1,2.5.2和2.5.3;
- 运行调试第4章编程示例4-3素因数;完成练习题4.3.1,4.3.2,4.3.3;
- 运行调试第4章编程示例4-5汉诺塔;完成练习题4.5.1,4.5.2。
三.示例代码:
1.第2章编程示例2-5减法游戏:
#include <iostream>
using namespace std;
int main() {
int total, n;
cout << "Welcome to NIM. Pick a starting total: ";
cin >> total;
while (true) {
// Pick best response and print results.
if ((total % 3) == 2) {
total = total - 2;
cout << "I am subtracting 2." << endl;
} else {
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0) {
cout << "I win!" << endl;
break;
}
// Get user's response; must be 1 or 2.
cout << "Enter number to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2) {
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: " << endl;
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0) {
cout << "You win!" << endl;
break;
}
}
system("PAUSE");
return 0;
}
2. 第4章编程示例4-3素因数:
#include <math.h>
#include <iostream>
using namespace std;
void get_divisors(int n);
int main() {
int n;
cout << "Enter a number and press ENTER: ";
cin >> n;
get_divisors(n);
cout << endl;
system("PAUSE");
return 0;
}
// Get divisors function
// This function prints all the divisors of n,
// by finding the lowest divisor, i, and then
// rerunning itself on n/i, the remaining quotient.
void get_divisors(int n) {
int i;
double sqrt_of_n = sqrt((double) n);
for (i = 2; i <= sqrt_of_n; i++)
if (n % i == 0) { // If i divides n evenly,
cout << i << ", "; // Print i,
get_divisors(n / i); // Factor n/i,
return; // and exit.
}
// If no divisor is found, then n is prime;
// Print n and make no further calls.
cout << n;
}
3.第4章编程示例4-5汉诺塔:
#include <cstdlib>
#include <iostream>
using namespace std;
void move_rings(int n, int src, int dest, int other);
int main()
{
int n = 3; // Stack is 3 rings high
move_rings(n, 1, 3, 2); // Move stack 1 to stack 3
system("PAUSE");
return 0;
}
void move_rings(int n, int src, int dest, int other) {
if (n == 1) {
cout << "Move from "<< src <<" to "<< dest << endl;
} else {
move_rings(n - 1, src, other, dest);
cout << "Move from "<< src <<" to "<< dest << endl;
move_rings(n - 1, other, dest, src);
}
}
- 实验1 C++函数
- C程序设计实验1
- C语言函数连接实验一
- C语言函数连接实验二
- TOJ 5307: C实验:素数判断函数
- TOJ 5238: C实验:变量交换函数
- 操作系统大型实验进展(7)-----C语言函数fopen
- 操作系统大型实验进展(8)-----C语言函数fread
- C库函数标准编程之fscanf()函数解读及其实验
- C语言实验七: 函数的程序设计-2
- C语言实验里用的一些时间函数
- 【c++】实验说明“转换构造函数”是如何转换的
- C++实验 实验1 函数与编译处理
- 实验1-2 printf函数的使用
- 实验1(友员函数)
- 【哈工大C作业实验】:13-1作业题
- c++-实验6--项目1-数组操作
- c语言结构体实验记录1
- 计算机图形学课件pdf版
- Python搭建PyQt5
- PHP Log时时查看小工具
- C++程序设计实验安排
- 整理网络各个协议
- 实验1 C++函数
- 点击页面其它地方隐藏该div的思路
- javascript的应用,简单设计切换网页主题的应用
- 实验3 文件操作
- 实验4 类初步
- CSS3的颜色
- windows7下安装centos双系统
- Apache错误日志时时查看
- 实验5 运算符重载