我试着让程序随机放一个颜色或一个数字。
如有任何帮助,我们将不胜感激。
提前感谢你不作恶。
我最初并没有使用函数,所以我创建了一个,但这并没有帮助。我还试着把I从0改成1。我以为一个简单的for循环会很容易
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int rand_num = rand();
int rand_color = rand() % 6; // should output color
int rand_distance = rand() % 5; // should output distance
int srand(time(NULL)); // initialize random seed
const string color[6] = { "red", "blue", "green", "orange", "yellow", "brown" };
const int distance[5] = { 7,25,20,10,15 };
void random_function()
{
if (rand_num % 2)
{
cout << color[rand_color];
}
else
cout << distance[rand_distance];
}
int main()
{
for (int i = 1; i < 30; i++)
{
random_function();
}
return 0;
}
你可能想要这样:
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
const string color[6] = { "red", "blue", "green", "orange", "yellow", "brown" };
const int distance[5] = { 7,25,20,10,15 };
void random_function()
{
// you must assign your variables each time
int rand_num = rand();
int rand_color = rand() % 6; // should output color
int rand_distance = rand() % 5; // should output distance
if (rand_num % 2)
{
cout << color[rand_color] << " "; // output also a space so make it readable
// the :: before distance is needed because
// distance is member of the std namespace
// and you have using namespace std;
}
else
{
cout << ::distance[rand_distance] << " "; // output also a space so make it readable
}
}
int main()
{
srand(time(NULL)); // call srand in main
for (int i = 1; i < 30; i++)
{
random_function();
}
return 0;
}
您使用全局变量的静态存储的方式是抛出异常,这些异常没有被捕获,您的代码没有被编译,我在下面修复了它。
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void random_function(int rand_num, int rand_color, int rand_distance, int srand, const string color[], const int distance[])
{
if (rand_num % 2)
{
cout << color[rand_color];
}
else
cout << distance[rand_distance];
}
int main()
{
int rand_num = rand();
int rand_color = rand() % 6; // should output color
int rand_distance = rand() % 5; // should output distance
int srand(time(NULL)); // initialize random seed
const string color[6] = { "red", "blue", "green", "orange", "yellow", "brown" };
const int distance[5] = { 7,25,20,10,15 };
for (int i = 1; i < 30; i++)
{
random_function(rand_num, rand_color, rand_distance, srand, color, distance);
cout << i << endl;
}
return 0;
}