在范围和特定步骤中生成C中的随机数 [英] Generate random number in C within a range and a specific step

查看:78
本文介绍了在范围和特定步骤中生成C中的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,很可能它将被标记为重复,但是我正在寻找答案,找不到相似的东西. 问题是:我想在特定范围内生成随机数[即min_value到max_value],并带有特定步骤.对于第一部分,答案是:

OK, most probably it will be marked as duplicated, but I am looking for an answer and cannot find something similar. The question is: I want to generate random numbers within a specific range [i.e. min_value to max_value] and with a specific step. For the first part the answer is:

int random_value = rand() % max_value + min_value;

该步骤如何定义?我想上述解决方案是在步骤1中得出的.对吗?举例来说,如果我想在第2步中生成数字(例如2、4,...,16),该怎么办?

The step how can I define it? I suppose that the above mentioned solution results in step 1. Correct? And if for example I want to generate the numbers with step 2 (e.g. 2, 4, ..., 16) what should I do?

推荐答案

这应该做您想要的:

int GetRandom(int max_value, int min_value, int step)
{
    int random_value = (rand() % ((++max_value - min_value) / step)) * step + min_value;
    return random_value;
}

这篇关于在范围和特定步骤中生成C中的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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