實驗1 C++函數

一.實驗目的:

  1. 掌握定義函數的方法、函數實參與形參的對應關係以及「值傳遞」的方式。
  2. 熟悉函數的嵌套調用和遞歸調用的方法。
  3. 熟悉全局變量、局部變量概念和使用方式。

二.實驗內容:ios

  1. 運行調試第2章編程示例2-5減法遊戲;完成練習題2.5.1,2.5.2和2.5.3;
  2. 運行調試第4章編程示例4-3素因數;完成練習題4.3.1,4.3.2,4.3.3;
  3. 運行調試第4章編程示例4-5漢諾塔;完成練習題4.5.1,4.5.2。

三.示例代碼:編程

  1.第2章編程示例2-5減法遊戲:ide

#include <iostream>函數

using namespace std;spa

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.ci

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;
}rem

 

  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); }}

相關文章
相關標籤/搜索