【问题标题】:Giving a random number to an array给数组一个随机数
【发布时间】:2013-06-01 22:32:26
【问题描述】:

大家好。我的代码发生了一件相当奇怪的事情。我想创建一个随机数输入到我的 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])
  • "rand() % 9 + 0;" - 0的原因是什么?

标签: c++


【解决方案1】:
 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

同时,你应该使用标题:

#include <ctime>

并删除

#include <stdlib.h>

因为你已经包含了&lt;cstdlib&gt;

【讨论】:

  • 谢谢,我确实看到了这个(并已修复),但是一旦插入任务,它就会在主网格中给我一个到多个 x
  • @Rijnhardt 你可能需要检查你的代码的逻辑,如果它没有给你预期的输出?
  • @Toacp 是我的 if 语句相互冲突吗?
  • @Toacp 谢谢,先生。我将第二个 if 语句更正为 else if 语句
  • @Rijnhardt 我没有看到任何冲突。但是,您 i == position[0] ==quest_position[0] && j == position[1] ==== quest_position[1],那么您将在屏幕上输出更多值,因为这两个 if 条件可能都为真。你可能需要 if/else if 代替?
【解决方案2】:

你错过了 == 排队

if(i == quest_position[0] && j == quest_position[1])

【讨论】:

    【解决方案3】:

    试试这个:

    if(i = quest_position[1] &amp;&amp; j == quest_position[1])

    【讨论】:

      猜你喜欢
      • 2018-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-17
      • 2011-09-18
      • 2018-10-04
      • 2012-02-10
      • 2020-10-21
      相关资源
      最近更新 更多