我有以下方法。方法rnd在两个边界之间返回一个随机整数:
/* Create next batch of 55 random numbers */
void advance_random (){
int j1;
double new_random;
for(j1=0; j1<24; j1++){
new_random = oldrand[j1]-oldrand[j1+31];
if(new_random<0.0){
new_random = new_random+1.0;
}
oldrand[j1] = new_random;
}
for(j1=24; j1<55; j1++){
new_random = oldrand[j1]-oldrand[j1-24];
if(new_random<0.0){
new_random = new_random+1.0;
}
oldrand[j1] = new_random;
}
} //advance_ramdom
/* Fetch a single random number between 0.0 and 1.0 */
double randomperc(){
jrand++;
if(jrand>=55){
jrand = 1;
advance_random();
}
return((double)oldrand[jrand]);
} //randomPerc
/* Fetch a single random integer between low and high including the bounds */
synchronized int rnd (int low, int high){
int res;
if (low >= high){
res = low;
} else {
res = low + (int)(randomperc()*(high-low+1));
if (res > high){
res = high;
}
}
return (res);
} // rnd
如何修改此值以使返回的数字mod2 = 0?
谢谢
答案 0 :(得分:8)
如果您可以获得[a, b]
范围内的随机数,那么您只需获取[(a+1)/2, b/2]
范围内的随机数并将其乘以2即可获得范围内的随机偶数{ {1}}
答案 1 :(得分:5)
使用bit-mask强制最低有效位为零:
x = x & ~1;
答案 2 :(得分:2)
将你从代码中得到的结果乘以两个结尾 - 仍然是随机的,然后将其除以2!
答案 3 :(得分:1)
如何使用:
return res & ~1;
答案 4 :(得分:0)
在Java 1.7或更高版本中,我会使用ThreadLocalRandom:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Get rid of Cascading Circular error on ModelBuilding
foreach (var relationShip in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
{
relationShip.DeleteBehavior = DeleteBehavior.Restrict;
}
#region Many-to-Many Employees Cases
modelBuilder.Entity<EmployeeCase>()
.HasKey(ec => new { ec.EmployeeId, ec.CaseId });
modelBuilder.Entity<EmployeeCase>()
.HasOne(ec => ec.Employee)
.WithMany(e => e.EmployeeCases)
.HasForeignKey(ec => ec.EmployeeId);
modelBuilder.Entity<EmployeeCase>()
.HasOne(ec => ec.Case)
.WithMany(c => c.EmployeeCases)
.HasForeignKey(ec => ec.CaseId);
#endregion
base.OnModelCreating(modelBuilder);
}
使用ThreadLocalRandom的原因解释为here。另请注意,我们对ThreadLocalRandom.nextInt()的输入+1的原因是为了确保max包含在范围内。