我有一块4 x 4的木板(16个正方形的值为0)。我必须在该板上选择一个随机正方形,并为该正方形生成一个随机值。
这是我的代码
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <sys/time.h>
using namespace std;
void pickSquare(int [][4]);
void printSquare(int [][4]);
int main() {
int a[4][4];
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
a[i][j] = 0;
for (int i = 0; i < 10; i++)
{
cout << endl << i << endl;
pickSquare(a);
printSquare(a);
}
}
void pickSquare(int a[][4]) {
struct timeval t1;
gettimeofday(&t1, NULL);
srand(t1.tv_usec * t1.tv_sec);
int randValue = rand() % 10;
if (randValue == 0 || randValue == 1) randValue = 4;
else randValue = 2;
int count = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
if (a[i][j] == 0) ++count;
int random = rand() % count;
cout << endl << "count = " << count;
cout << endl << "random = " << random;
count = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
if (a[i][j] == 0) {
if (count == random) {
a[i][j] = randValue;
cout << endl << " " << i << " " << j << endl;
break;
}
++count;
}
if (count == random) break;
}
}
void printSquare(int a[][4]) {
cout << endl;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
函数
pickSquare(int [][4])
用于选择一个随机Square,并生成一个随机值。功能
printSquare(int [][4])
用于以4 x 4的比例印刷电路板。我认为一切都很好,但是当我运行程序时,有时程序不会选择任何正方形。因此,完成功能后,板仍然相同。
谁能解释为什么?
最佳答案
我认为问题是
if (count == random) break;
当内部循环完成时,您可以在此处进行未经测试的计数。