dpxw7293 2013-09-23 10:23
浏览 80

向变量添加/减去随机数

I want to create some random sql data with a php script

currently I get the last record, generate a random number between 1 and 2 ... if its a 1 I will add a random number to the record else if its a 2 i will subtract a random number from

the problem is it keeps spitting out minus random numbers! I only want positive random numbers.

$result = mysql_query("SELECT * FROM Data ORDER BY id DESC") 
    or die(mysql_error()); 

while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table

    $temp=$row['temp'];
    $light=$row['light'];

};

$name="Herbi";
$date=Date("o:m:d");
$time=Date("H:i:s");

$rand =rand(1,2);
$randnu =rand(1,10);

echo " rand:".$rand;
switch($rand){

    case 1:
        $temprand=$temp+$randnu;
        $lightrand=$light+$randnu;
    break;

    case 2:
        $temprand=$temp-$randnu;
        $lightrand=$light-$randnu;
    break;
};
echo"";
echo"randnu";
echo $randnu;
echo "   ";
echo"lightrand";
echo $lightrand;
  • 写回答

1条回答 默认 最新

  • dongmiao4733 2013-09-23 10:46
    关注

    Based on your code this is valid, if your $temp=1 and $rand=2 then $temprand will be -1.

    You can add a check that your $temp and $light should always be greater than or equal the max random numbers so when you minus the (max of) random number from $temp or $light you will end up with 0.

    if($row['temp']>=2){
      $temp=$row['temp'];
    }else{
      $temp=2; //Max of $rand =rand(1,2);
    }
    

    or shorthand

    $temp=($row['temp'] >= 2? $row['temp'] : 2);
    $light=($row['light'] >= 10? $row['light'] : 10);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么