摆脱会议中的“除以零”警告

时间:2016-04-13 15:41:55

标签: php session

这是一个猜测数字的游戏,我希望页面通过使用会话来跟踪胜利,损失和总数以及获胜的百分比。我想点击“重置”时重置所有内容,但是当我点击重置时,一切都等于零,并且会有一个警告说“除以零”。我如何重新排列这个PHP,只在游戏进行时进行%计算,而不是在重置时进行?

<?php 
// initialize wins and losses
if ($_SESSION['wins'] == "") { 
    $_SESSION['wins'] = 0;
}
if ($_SESSION['losses'] == "") { 
    $_SESSION['losses'] = 0;
}

echo "<h1>PHP SESSIONS</h1>";

if ($_GET['reset'] == "yes") {
    $_SESSION['wins'] = 0;
    $_SESSION['losses'] = 0;
    $_SESSION['total'] = 0;
    echo "<p>The game has been reset.</p>";
} else {
    $randNum = rand(1,5);
    echo "<p>The random number is <b>" . $randNum . "</b></p>";
    if ($randNum == 3) {
        echo "<p>The number equalled 3. YOU WIN!</p>";
        $_SESSION['wins']  = $_SESSION['wins']  + 1;
    } else {
        echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
        $_SESSION['losses']  = $_SESSION['losses']  + 1;
    }
    $_SESSION['total']  = $_SESSION['total']  + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;

echo "<p>WINS: " . $_SESSION['wins'] . " |  LOSSES: " . $_SESSION['losses'] . "|  TOTAL: " . $_SESSION['total'] . "</p>";
echo "<p>Percentage of Winning:     ". $_SESSION ['percentage'] . " % </p>"
?>

<a href="playing-with-sessions.php" class="button"> ROLL AGAIN :) </a> 
<a href="playing-with-sessions.php?reset=yes" class="button"> RESET :) </a> 

2 个答案:

答案 0 :(得分:1)

向上移动您要分割的线:

.sec--hero {
    background-image: url(http://przedszkole.pwoj.pl/wp-content/themes/twentysixteen/img/bg-orange.png);
    background-repeat: repeat;
	overflow:hidden;
}

将它放在else括号内。一旦我重新格式化了代码,就很容易看出问题所在。我建议总是使用适当的缩进。 :)

答案 1 :(得分:1)

满足$_GET['reset'] == 'yes'时,您正在设置$_SESSION['total'] = 0

然后,您将$_SESSION['wins']除以下一行0$_SESSION['total'](无论$_SESSION['total']的当前状态如何都会执行:

$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100 ;

当代码格式正确时,更容易看到发生了什么。看看:

if ($_GET['reset'] == "yes") { // reset called
    $_SESSION['wins'] = 0;
    $_SESSION['losses'] = 0;
    $_SESSION['total'] = 0; // set to zero(0)
    echo "<p>The game has been reset.</p>";
} else {
    $randNum = rand(1,5);
    echo "<p>The random number is <b>" . $randNum . "</b></p>";
    if ($randNum == 3) {
        echo "<p>The number equalled 3. YOU WIN!</p>";
        $_SESSION['wins']  = $_SESSION['wins']  + 1;
    } else {
        echo "<p>The number did NOT equal 3. YOU LOSE!</p>";
        $_SESSION['losses']  = $_SESSION['losses']  + 1;
    }
    $_SESSION['total']  = $_SESSION['total']  + 1;
}
$_SESSION ['percentage'] = (($_SESSION['wins']) / ($_SESSION['total'])) * 100; // chance that $_SESSION['total'] is zero(0)

再次,当您调用重置操作时,$_SESSION['total']的值为int(0)。然后在脚本中,然后除以int(0),给出有问题的错误。有意义吗?

因此,首先需要确保$_SESSION['total']大于0,然后再将其除去。{/ p>