所以我试图找出为什么我的计数器总是乘以大小, 而不是一个小数字,因为" if"我使用的声明只应在它们相同的时候增加计数器,但是由于我使用了随机数,因此每个值肯定不一样。编辑:对不起,这是我试图构建的完整代码。
#include <iostream>
#include <ctime>
using namespace std;
void arrayList (int array[],int array2[], int size, double times)
{
int counter =0;
for (int k = 0; k < times; k++)
{
for (int i = 0; i < size; i++)
{
array[i] = rand();
array2[i] = rand();
if (array[i] == array2[i])
{
counter = counter + 1;
}
}
}
cout << counter << endl;
}
int main ()
{
srand (1);
double times = 0;
int size;
cout << "Enter number of times: ";
cin >> times;
cout << "Enter minimum number of persons: ";
cin >> size;
int arrays[size];
arrayList(arrays,arrays, size, times);
}
答案 0 :(得分:0)
这是我重新安排代码的方式:
#include <iostream>
#include <vector>
#include <ctime>
int arrayList(std::vector<int> array1, std::vector<int> array2, int size, double times)
{
int counter = 0;
for (int k = 0; k < times; k++)
{
for (int i = 0; i < size; i++)
{
array1[i] = rand();
array2[i] = rand();
std::cout << "1st vector: " << array1[i] << " 2nd vector: " << array2[i] << std::endl;
if (array1[i] == array2[i])
{
counter++;
}
}
}
return counter;
}
int main()
{
srand((unsigned)time(NULL));
double times = 0;
int size = 0;
std::cout << "Enter number of times: ";
std::cin >> times;
std::cout << "Enter minimum number of persons: ";
std::cin >> size;
std::vector<int> array(size);
std::cout << arrayList(array, array, size, times);
}
我使用向量代替数组(但你也可以使用动态分配的数组)。
请尝试发布反馈!