#include<time.h>#include<stdlib.h>#include<stdio.h>void main(){ srand((unsigned)time(NULL)); //用当前系统时间设置种子 int a[10]; int b[8]; printf("随即初始化a数组的10个数(范围是0~10).\n"); for(int i=0;i<10;i++){ a[i]=rand()%11; //用rand函数生成0-10的随机数并赋值给数组a[i] printf("%4d",a[i]); if(i%10==0 && i!=0) printf("\n");} printf("随即初始化b数组的8个数(范围是0~8).\n"); for (int j=0;j<8;j++){ b[j] =rand()%8; printf("%4d", b[j]); if(i%8==0 && i!=0) printf("\n"); } getchar();}
5 回答
snowmanJS
TA贡献89条经验 获得超53个赞
#include <iostream> #include <time.h> #include <stdlib.h> #include <vector> using namespace std; //生成数组 int *createArr(int *arr, int size) { srand((unsigned)time(NULL)); for (int i = 0;i < size;++i) arr[i] = rand() % (size+1); return arr; } //打印数组 void printArr(int *arr, int size) { for (int i = 0;i <size; ++i) cout << arr[i] << " "; cout << endl; } //若数组中的元素被比较过返回true bool isRet(const vector<int> ret, int val) { bool flag = false; auto beg = ret.cbegin(); auto ending = ret.cend(); while(beg!=ending) { if (val == *beg) { flag = true; break; } ++beg; } return flag; } //查找比对 void findSameElement(int *arr1, int size1, int *arr2, int size2) { vector<int> flag; int cntArr1 = 1; int cntArr2 = 0; for (int i = 0;i < size1;++i) { if (isRet(flag, arr1[i])) { continue; } cout << "arr1[" << i << "]"; for (int j = i + 1;j < size1;++j) { if (arr1[i] == arr1[j]) { cout << "=arr1[" << j << "]"; ++cntArr1; } } for (int k = 0;k < size2;++k) { if (arr2[k] == arr1[i]) { cout << "=arr2[" << k << "]"; ++cntArr2; } } cout<<"="<<arr1[i] <<endl; cout << arr1[i] << "一共出现" << cntArr1 + cntArr2 << "次,其中在arr1中出现" << cntArr1 << "次,在arr2中出现" << cntArr2 << "次" << endl; cout << "----------------------------------------------------------" << endl; flag.push_back(arr1[i]); for (auto val : flag) cout << val << " "; cout << endl; cntArr1 = 1; cntArr2 = 0; } } int main() { const int N1 = 10;//定义arr1的维度,数值可以任意改 const int N2 = 8;//定义arr2的维度,数值可以任意改 int arr1[N1]; int arr2[N2]; //生成两个数组 createArr(arr1, N1); createArr(arr2, N2); //打印两个数组 cout << "arr1:" << endl; printArr(arr1, N1); cout << "arr2:" << endl; printArr(arr2, N2); //输出结果 cout << "比对结果:" << endl; findSameElement(arr1,N1, arr2, N2); system("pause"); return 0; }
- 5 回答
- 1 关注
- 2132 浏览
添加回答
举报
0/150
提交
取消