为什么(rand()%任何东西)总是0在C ++? [英] Why is (rand() % anything) always 0 in C++?

查看:499
本文介绍了为什么(rand()%任何东西)总是0在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法让rand()在C ++中工作。 rand()通常给我一个非常大的数字。当我尝试使用模运算符(%)给它一个范围,它总是返回0,无论什么。

I am having trouble getting rand() to work in C++. rand() normally gives me a very large number. When I try to use the modulo operator (%) to give it a range, it always returns 0, no matter what.

在程序开始时播种随机数生成器也无济于事。

Seeding the random number generator at the beginning of the program doesn't help either.

推荐答案

以下代码适用于我(每次运行时会发出一个包含0和1000之间的随机数):

The following code works just fine for me (emitting a random number between 0 included and 1000 excluded each time it's run):

#include <cstdlib>
#include <ctime>
#include <iostream>

int main()
{
    std::srand(time(0));
    std::cout<<(std::rand() % 1000)<<std::endl;
    return 0;
}

这篇关于为什么(rand()%任何东西)总是0在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆