gpt4 book ai didi

c++ - 给数组一个随机数

转载 作者:行者123 更新时间:2023-11-30 02:54:45 24 4
gpt4 key购买 nike

大家好。我的代码发生了一件相当奇怪的事情。我想创建一个随机数以输入到我的 quest_postition 数组中,以便在我的网格数组中使用它。我希望每次运行程序时位置都不同。

它目前正在做的是进入一个无限循环并一直向下显示网格。

这是我的代码:

#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <time.h>


using namespace std;

void draw_grid()
{

char grid[9][9] = { {'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'},
{'x','x','x','x','x','x','x','x','x'}};
char character = '*';
char quest = 'Q';

int position[2] = {4,4};
int quest_position[2];

srand(time(NULL));

quest_position[0] = rand() % 9 + 0;
quest_position[1] = rand() % 9 + 0;

char direction;

for(int i = 0; i < 9; i++){
for (int j = 0; j < 9; j++){
if(i == position[0] && j == position[1])
cout << character;
if(i = quest_position[0] && j == quest_position[1])
cout << quest;
else
cout << grid[i][j];
cout << " ";
}
cout << endl;
}
}

int main()
{
draw_grid();
}

请你帮忙。

谢谢。

最佳答案

 if(i = quest_position[0] && j == quest_position[1])
cout << quest;

应该是:

 if(i == quest_position[0] && j == quest_position[1])
//^^^Error here should be logical equal
cout << quest;

您可以在这里找到现场演示:Code Demo

同时,你应该使用header:

#include <ctime>

并移除

#include <stdlib.h>

因为您已经包含了 <cstdlib> .

关于c++ - 给数组一个随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16873337/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com