2013-03-01 34 views
2

如何创建一个程序,可以从1→RAND_MAX生成10个随机数?如何定义RAND_MAX

RAND_MAX必须是用户输入的数字。

int main() 
{ 
using namespace std; 
int x; 
int y; 
Random: 
{ 
x = rand(); 
cout << x << endl; 
} 
y = y + 1; 
if (y == 10) { 
    return 0; 
} 
goto Random; 
} 
+0

对不起,但程序不会出现,它应该在那里,很难。 – Lemonizer 2013-03-01 14:35:33

+5

RAND_MAX由std库定义http://en.cppreference.com/w/cpp/numeric/random/RAND_MAX – 2013-03-01 14:44:40

+0

可能的重复[Random number C++ in some range](http://stackoverflow.com/questions/7560114)/random-number-c-in-some-range) – 2013-03-01 14:53:50

回答

3

喜欢的东西:

int main() 
{ 
    int randMax; 
    cin >> randMax; 
    for (int y = 0; y < 10; y++) 
    { 
    int x = rand() % randMax; // Range = [0, randMax) 
    cout << x+1 << endl; // Range = [1, randMax] 
    } 
} 

哦,你尽量避免goto(至少在我看来)。这里有关于它的twoquestions

+0

谢谢! 但是我到底在哪里放这个,并且它应该取代什么?另外为什么我不能使用“goto”?我的唯一编程经验是用TI-84,并且我一直使用goto,RandInt()就是它所称的TI 计算器非常简单:P – Lemonizer 2013-03-01 14:43:38

+0

And don不会使用大写字母作为局部变量。 – 2013-03-01 14:43:55

+0

这不会编译'RAND_MAX'被定义在与'rand'相同的头文件中,并且会被一个数字 – 2013-03-01 14:45:28