【发布时间】:2012-08-04 21:15:48
【问题描述】:
你能帮我解决一个用随机数填充一个由 5 个圆组成的数组的问题吗? 随机数将是圆的半径。 这是我的代码:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
// Array 2, below section is to populate the array with random radius
float CircleArrayTwo [5]; // store the numbers
const int NUM = 5; // Display 5 random numbers
srand(time(NULL)); // seed the generator
for(int i = 0; i < NUM; ++i)
{
CircleArrayTwo[i] = rand()%10;
}
cout << "Below is the radius each of the five circles in the second array. " << endl;
cout << CircleArrayTwo << endl;
system("PAUSE");
return 0;
}
目前输出如下:
下面是第二个数组中五个圆的半径。 002CF878
我哪里出错了?
非常感谢任何帮助
【问题讨论】:
-
在 C++ 中,您应该使用
<ctime>而不是<time.h>标头(对于所有其他 C 标准标头也是如此)。此外,将整个命名空间导入全局命名空间通常是一种不好的做法,因此不要使用using namespace std;,而只是完全限定您的名称(例如,std::cout而不仅仅是cout)。使用endl会添加换行符并刷新流,这会降低性能。通常您不需要刷新,因此默认情况下您只需使用'\n'代替endl。如果您使用的是 C++11 编译器,请使用<random>库而不是srand()和rand()