相关疑难解决方法(0)

为什么rand()%7总是返回0?

这似乎是一个非常奇怪的问题:

这是我的代码:

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        srand((unsigned int)time(NULL));
        int newRandomNumber = 0;
        newRandomNumber = rand() % 7;
        NSLog(@"%d", rand() % 7); //This prints out what I expected
        NSLog(@"newRandomNumber = %d", newRandomNumber); // This always prints out 0!
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我替换那一行说

newRandomNumber = rand() % 7
Run Code Online (Sandbox Code Playgroud)

同

newRandomNumber = rand() % 8
Run Code Online (Sandbox Code Playgroud)

一切都很完美.为什么会这样?

c random objective-c

35
推荐指数
2
解决办法
5359
查看次数

Rand()%14仅生成值6或13

每当我运行以下程序时,返回的值总是6或13.

#include <iostream>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;

//void randomLegs();
//void randomPush();
//void randomPull();
//void randomMisc();


int main(int argc, const char * argv[])
{
    srand(time(NULL));
    //randomLegs();
    cout << rand() % 14;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在今天和昨天,我已经将程序运行了近百次.

谁能告诉我我做错了什么?

谢谢.

编辑:顺便说一句,如果我将rand()的范围改为13或15,它就可以了.

c++ random srand

14
推荐指数
2
解决办法
916
查看次数

无偏随机数发生器

我使用以下代码在域中生成随机数.当我绘制它们时,它们看起来分组在右边.我可以告诉你我的情节,但我不知道如何上传它.基本上我将一些数据值与相应的点相关联.你能告诉我怎样才能纠正它?我的完整代码是

#include <iostream>
#include <cmath>
#include <fstream>
#include <sstream>
#include <string>
#include <cstdlib>
#include <cstdio>
#include <time.h>

using namespace std;
string int2string1( int l );
string int2string2( int m );
int main ()
{
    ofstream outFile;
    ofstream myimp;
    string filename;
    srand((unsigned)time(0));
    int nx = 400;
    int ny = 200;
    int i,j,ix,iy,xm,ym,nimp,nfam[nx][ny];
    float vo,rnd,rr,rad,sig,vimp[nx][ny];
    for (i=0; i<nx; i++)
    {
        for (j=0; j<ny; j++)
        {
            vimp[i][j] = 0.0;
        }
    }
    rad = 5.0;
    xm = 0;
    ym = 0;
    vo = 0.08; …
Run Code Online (Sandbox Code Playgroud)

c++ random

3
推荐指数
2
解决办法
1944
查看次数

如何在arc4random中排除数字?

我使用arc4random来生成一个随机数.我想在1-9之间生成一个数字.如何排除0?

int r = arc4random() % (9);
    NSLog(@"Random Number: %d",r);
Run Code Online (Sandbox Code Playgroud)

c random integer objective-c arc4random

0
推荐指数
2
解决办法
4797
查看次数

标签 统计

random ×4

c ×2

c++ ×2

objective-c ×2

arc4random ×1

integer ×1

srand ×1