我想这样做
我有两个数字,A 和 B,其中 A 可以大于或小于 B。我想要做什么:
比较 B 和 A
如果他们的比率在范围之外,则取一个随机数并将其添加到“A” - 现在检查他们的新比率是否满足条件
0.95 < ratio < 1.05
如果没有,请尝试另一个随机数。
我的问题是我遇到了无限循环......这就是我所做的:
float ratio = A/B;
if (ratio < 0.95 || ratio > 1.05) {
do {
// randomly take a negative or positive number
float random_n = ((float)rand())/RAND_MAX - 0.50;
// get an even smaller step
random_n *= 0.1;
// add or subtract the random number (depending on its sign)
A += random_n;
// form the ratio again
ratio = A / B;
cout << "lets see " << A << " " << B << " " << ratio << endl;
}
while (ratio > 0.95 || ratio < 1.05);
}