WHCSRL 技术网

菜学C++ Day36

  • 随机数rand(),头文件 
    #include<stblib.h>
            用法: int x=rand()%%a+b,表示x为[b,a-1+b],小数直接先得位数,再除10、100等就可以了

            一般要用到随机数种子srand(seed)
            其中seed一般为time(0),随时间变化
    1. #include<time.h>
    2. srand(time(0));

        time(0)指函数返回当前时间,如果发生错误返回0
        time(1)…………………………………………返回1

  •  setw()默认右对齐
  •  P90 例4-14行指针传递二维数组 函数输入输出

    1. #include<iostream>
    2. #include<stdlib.h>
    3. #include<time.h>
    4. #include<iomanip>
    5. using namespace std;
    6. //行指针传递
    7. void input(int p[][4], int n) {
    8. for (int i = 0; i < n; i++) {
    9. for (int j = 0; j < 4; j++)
    10. p[i][j] = rand() %% 100 + 1;
    11. }
    12. }
    13. void output(int (*p)[4], int n) {
    14. cout << "随机生成的二维数组为:" << endl;
    15. for (int i = 0; i < n; i++) {
    16. for (int j = 0; j < 4; j++)
    17. cout <<setw(4)<< p[i][j];
    18. cout << endl;
    19. }
    20. }
    21. int main() {
    22. int a[3][4];
    23. //定义行指针 数据类型 (*指针变量名)[二维数组列数]
    24. int(*p)[4]=a;
    25. //时间若返回错误,则返回0
    26. srand(time(0));
    27. input(a, 3);
    28. output(p, 3);
    29. return 0;
    30. }

推荐阅读