实验2 C++数组与指针
一.实验目的:
-
掌握一维数组和二维数组的定义、赋值和输入输出的方法。
-
掌握字符数组和字符串函数的使用。
-
通过实验进一步掌握指针的概念,会定义和使用指针变量。
-
能正确使用数组的指针和指向数组的指针变量。
-
能正确使用字符串的指针和指向字符串的指针变量。
-
能正确使用引用型变量。
二.实验内容:
- 运行调试第5章编程示例5-3,5-4,5-5扑克发牌程序;完成练习题5.3.1,5.4.1, 5.5.1和7.5.2;
- 运行调试第6章编程示例6-3数组排序器;完成以下练习:
- 改进sort函数;
- 用vector改造程序,使其支持变长数组;
- 用char类型来改造程序具有更好输入方式,使其能一次性输入多个数组元素;
- 用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; }