【问题标题】:How do I create a list or Array in C++ and then randomly assign those objects to another variable?如何在 C++ 中创建一个列表或数组,然后将这些对象随机分配给另一个变量?
【发布时间】:2015-12-09 17:57:16
【问题描述】:

我真的不确定我应该使用哪种方法。但下面是我正在制作的关于汽车通过红绿灯的脚本。并且一旦经过一定数量的汽车,灯光就会从绿色变为黄色,从黄色变为红色。

要为汽车添加一些功能,我想为它们分配 4 种颜色中的 1 种。我创建了一个数组,但是当我运行程序时,它看起来像是将数组分配给我的输出而不是颜色,它为每个“汽车”添加了一个奇怪的代码。

如果这不是解决这个问题的方法,还有什么更好的方法?

#include <iostream>
#include <string>
#include <windows.h> //Allow to import Sleep()
using namespace std;

void main()

{
    int cars = 0;
    string go, light;
    string testArray[4] = { "Red", "Green", "Blue", "White" }; //Car colors to assign to cars passing

    cout << "The light is green \n"
        << "Type go and press enter to start cars" << endl;
    cin >> go;
    cout << "Cars that have passed the light. \n";

    do
    {
        cout << cars << " " << testArray << endl;
        cars++;
        Sleep(1000); //Delay output for 1 second
    } while (cars < 6);
    {

        cout << "Yellow light" << endl;
        cout << "There are " << cars + 10 << " cars slowing down." << endl; //cars + 10 cars slowing down on yellow light.
    }

    cout << "The light is red. There are " << cars << " cars stopped.\n";

}

输出如下

The light is green
Type go and press enter to start cars
go
Cars that have passed the light.
0 007CF72C
1 007CF72C
2 007CF72C
3 007CF72C
4 007CF72C
5 007CF72C
Yellow light
There are 16 cars slowing down.
The light is red. There are 6 cars stopped.
Press any key to continue . . .

【问题讨论】:

  • 既然您似乎在 Windows 上,this 应该会有所帮助。否则,请使用rand。只需将随机数作为索引传递给您的数组。另外,请确保它不超过数组的大小:例如。 testArray[randomNumber%sizeOfArray].
  • 我知道你才刚刚开始。但由于这被标记为 C++,因此请尝试更多地考虑对象。光是一个物体。 (所以让它成为一个类!)它有一个属性,颜色;也许它还可以跟踪自上次变绿以来经过的汽车数量。然后它会在 N 辆汽车之后自行改变颜色。

标签: c++ arrays list


【解决方案1】:

制作一个整数来保存颜色的索引。

int color_index;
do
    {
        color_index=rand()%4;
        cout << cars << " " << testArray[color_index] << endl;
        cars++;
        Sleep(1000); //Delay output for 1 second
    } while (cars < 6);

您还可以包含“srand(time(NULL));”在 main() 中确保每次运行程序时都会给你不同的随机颜色(顺序不同)。

【讨论】:

  • 所有很棒的答案都会导致同样的事情!感谢您在这里的这一点,工作完美!根本没想到会为他们创建索引。我可以完成剧本!
【解决方案2】:

您正在打印数组本身,而不是它的成员,这就是为什么您会得到奇怪的数字,所有这些都是内存地址。请改用array[index],并使用rand() % ARRAY_SIZE 之类的方法来获取随机索引。

【讨论】:

    猜你喜欢
    • 2021-05-06
    • 2021-07-27
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    相关资源
    最近更新 更多