實驗2 C++數組與指針

一.實驗目的:

    1. 掌握一維數組和二維數組的定義、賦值和輸入輸出的方法。ios

    2. 掌握字符數組和字符串函數的使用。編程

    3. 經過實驗進一步掌握指針的概念,會定義和使用指針變量。數組

    4. 能正確使用數組的指針和指向數組的指針變量。dom

    5. 能正確使用字符串的指針和指向字符串的指針變量。函數

    6. 能正確使用引用型變量。oop

二.實驗內容:

  1. 運行調試第5章編程示例5-3,5-4,5-5撲克發牌程序;完成練習題5.3.1,5.4.1, 5.5.1和7.5.2;
  2. 運行調試第6章編程示例6-3數組排序器;完成如下練習:
    1. 改進sort函數;
    2. 用vector改造程序,使其支持變長數組;
    3. 用char類型來改造程序具備更好輸入方式,使其能一次性輸入多個數組元素;
    4. 用string類型來改造程序具備更好輸入方式,使其能一次性輸入多個數組元素;

三.示例代碼:

  1.第5章編程示例5-3撲克發牌程序:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;

int rand_0toN1(int n);
void draw_a_card();

char *suits[4] = {"hearts", "diamonds", "spades", "clubs"};
char *ranks[13] = {"ace", "two", "three", "four", "five",
"six", "seven", "eight", "nine",
"ten", "jack", "queen", "king" };

int main() {
int n, i;

srand(time(NULL)); // Set seed for random numbers.

while (1) {
cout << "Enter no. of cards to draw (0 to exit): ";
cin >> n;
if (n == 0)
break;
for (i = 1; i <= n; i++)
draw_a_card();
}
return 0;
}

// Draw-a-card function
// Performs one card-draw by getting a random 0-4 and a random
// 0-12. These are then used to index the string arrays, ranks
// and suits.
//
void draw_a_card() {
int r; // Random index (0 thru 12) into ranks array
int s; // Random index (0 thru 3) into suits array

r = rand_0toN1(13);
s = rand_0toN1(4);
cout << ranks[r] << " of " << suits[s] << endl;
}

// Random 0-to-N1 Function.
// Generate a random integer from 0 to N-1.
//
int rand_0toN1(int n) {
return rand() % n;
}

  

  2.第6章編程示例6-3數組排序器:

#include <iostream>
using namespace std;

void sort(int n);
void swap(int *p1, int *p2);

int a[10];

int main () {
int i;

for (i = 0; i < 10; i++) {
cout << "Enter array element #" << i << ": ";
cin >> a[i];
}
sort(10);

cout << "Here are all the array elements, sorted:" << endl;
for (i = 0; i < 10; i++)
cout << a[i] << " ";

cout << endl;
system("PAUSE");
return 0;
}

// Sort array function: sort array named a, having n elements.
// 
void sort (int n) {
int i, j, low;

for(i = 0; i < n - 1; i++) {

// This part of the loop finds the lowest
// element in the range i to n-1; the index
// is set to the variable named low.

low = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[low])
low = j;

// This part of the loop performs a swap if
// needed.

if (i != low)
swap(&a[i], &a[low]);
}
}

// Swap function.
// Swap the values pointed to by p1 and p2.
//
void swap(int *p1, int *p2) {
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
相關文章
相關標籤/搜索