我有以下代码,它给出了一个随机数学问题,我试图从rand标签中得到偶数数字,并使第一个数字高于第二个数字。
<?php
//set the sum
$operarors = array( '+','-');
$operator = $operarors[rand(0,1)];
//random the numbers
$numberone = rand(4,10);
$numbertwo = rand(2,4);
//get the answer
if ($operator == '-') {
$answer1 = $numberone - $numbertwo;
}
if ($operator == '+') {
$answer1 = $numberone + $numbertwo;
}
if ($operator == 'x') {
$answer1 = $numberone * $numbertwo;
}
if ($operator == '/') {
$answer1 = $numberone / $numbertwo;
}
echo "Question: $numberone $operator $numbertwo<br>";
echo "<br>";
echo $answer1;
?>
我查看了random function,似乎无法找到我需要的两个问题的信息
要将第一个数字的值固定为高于我告诉它的第二个数字的值为4到10之间的随机数,并要求第二个数字为2到4之间的随机数
$numberone = rand(4,10);
$numbertwo = rand(2,4);
但是对于这段代码的功能,我希望我不需要这样做。
这背后的原因是如果第一个数字是4而第二个数字是5则答案是-1。 这将是我的小女儿帮助她的数学,并没有教 - 这个数字很早:)
随机偶数我已经结束了我的思考,因为我已经尝试google找到问题的答案而没有找到任何工作
你可以告诉我不是php的专家,所以请多给一点经验,这样我就可以获得更好的知识
提前致谢
答案 0 :(得分:2)
要获得一个甚至可以执行以下操作的随机数:
$max = 10;
echo $evenRandomNb = rand(0, round(($max / 2), 0, PHP_ROUND_HALF_DOWN)) * 2;
要获得2个随机数,其中一个大于第二个(从不相等),请执行:
$max = 10;
echo $firstNb = rand(0, $max - 1);
echo $secondNb = rand($firstNb + 1, $max);
您可能希望将两种方法结合起来得到两个偶数,第二个比第一个更大:
$max = 10;
echo $firstNb = rand(0, round((($max - 1) / 2), 0, PHP_ROUND_HALF_DOWN)) * 2;
echo $secondNb = rand(round((($firstNb + 2) / 2), 0, PHP_ROUND_HALF_DOWN), round(($max / 2), 0, PHP_ROUND_HALF_DOWN)) * 2;
答案 1 :(得分:0)
只需执行rand()
,然后乘以2(保证偶数),将它们放在一个数组中,arsort()
它们(按降序排列)
$numbers = arsort(array(
rand(0,5)*2,
rand(0,5)*2
));
if($numbers[0] == $numbers[1]) {
$numbers[1]+=2; // if you need them to be not equal
}
echo 'This is number one: ' . $numbers[0] . '.<br>';
echo 'This is number two: ' . $numbers[1] . '.';