【问题标题】:Number counter game数字计数器游戏
【发布时间】:2020-08-05 21:55:15
【问题描述】:

我正在尝试制作一个随机数计数器游戏,该游戏使用 for 循环打印出 6 个随机数 1 - 6。我想制作它,以便代码可以说明数字 6 在循环中显示的次数。

目前我有它为 6 个随机数的循环打印出来的代码,但它只计算打印出来的数字。

例如 欢迎来到骰子游戏! 你会掷多少个六分球? 4 2 4 6 4 6 你掷出了 2 个六(es)!

<?php

echo"<h1>Welcome to the guess game thing guess how many 6s!</h1>";
$counter = 0;

for ($i=0; $i <=6;$i++) { 
    $randomNum = rand(1,6);

    if ($randomNum <= 6) {
        echo "<br> $randomNum";
        $counter++;
    }

    else
    {
        echo"$randomNum  <br>";

    }
}

echo"<br>You rolled $counter sixes";

【问题讨论】:

  • 检查 6 是否使用小于或等于 - 尝试将其更改为 if ($randomNum == 6) {
  • 我改变了,但现在我的 for 循环搞砸了,请看下面的截图gyazo.com/f95d1c611cf4850098317246a27930ac
  • 您需要在放置&lt;br&gt; 标签的位置保持一致。

标签: php for-loop if-statement counter


【解决方案1】:

一些微小的变化,但你几乎就在那里。与您的换行符保持一致并验证您专门检查 6

$numberToMatch = 6;
for ($i = 0; $i <= 6; $i++) { 
    $randomNum = rand(1,6);

    if ($randomNum == $numberToMatch) {
        $counter++;
    }

    echo "$randomNum <br>";
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    $num = $_POST["num"];
    
    for ($i=0; $i <=100;$i++) { 
        $randomNum = rand(1,10);
    
        if ($randomNum == $num) {
            echo $randomNum;
            break;
        }
    
        echo $randomNum;
    
    }
    
    echo"<h2> there are $i</h2>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-02
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 2016-04-29
      • 2017-07-10
      • 2017-02-18
      • 2017-04-11
      相关资源
      最近更新 更多