实验2 C++数组与指针
2017-03-10 17:43
190 查看
一.实验目的:
掌握一维数组和二维数组的定义、赋值和输入输出的方法。掌握字符数组和字符串函数的使用。
通过实验进一步掌握指针的概念,会定义和使用指针变量。
能正确使用数组的指针和指向数组的指针变量。
能正确使用字符串的指针和指向字符串的指针变量。
能正确使用引用型变量。
二.实验内容:
运行调试第5章编程示例5-3,5-4,5-5扑克发牌程序;完成练习题5.3.1,5.4.1, 5.5.1和7.5.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; }
相关文章推荐
- 实验2 C++数组与指针
- 16周实验报告3:用指针完成14周任务2
- C++数组与指针概念
- 实验9 指针1 1、程序填空:下列程序在数组中同时查找最大元素和最小元素的下标,分别存放在 main()函数的max 和 min 变量中。要求:根据运行结果分析程序和填空,并注释说明填充依据。
- 实验十 指针2
- 实验11——指针的基础应用
- 实验12——指针的基础应用2
- C++数组指针、指针数组、函数指针的核心概念
- 实验9 指针1
- 实验9 指针1
- 实验10 指针2。
- 实验10 指针2 加密处理
- C++数组以及指针学习的技巧
- C++数组(二维数组)与指针 以及 函数传递/返回指针和数组参数
- C++学习之路(40)---C++数组指针、指针数组、函数指针的核心概念
- 实验12——指针的基础应用2
- c++数组,引用和指针
- 实验9 指针1
- [C++]指针运算中关于*和&符号的运算实验
- 实验9-1 指针类型