【发布时间】: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 . . .
【问题讨论】:
-
我知道你才刚刚开始。但由于这被标记为 C++,因此请尝试更多地考虑对象。光是一个物体。 (所以让它成为一个类!)它有一个属性,颜色;也许它还可以跟踪自上次变绿以来经过的汽车数量。然后它会在 N 辆汽车之后自行改变颜色。