因此,我正在學習PHP,因此,正試圖創建一個程序來簡化分數(至少可以說是一個非常初學者的代碼)。它使用HTML表單,從中抽取分子和分母。但是,在提交表格時,功能將輸出的數字吐出。我的想法是,它正在傳遞每個函數中的'for'循環。任何幫助將不勝感激。爲什麼循環不循環?
<html>
<head>
<!-- CSS for echoed data -->
<style>
p {
text-size:12px;
text-color:black;
}
</style>
</head>
<body>
<!-- Defines Form -->
<form method = "post" action = "<?php echo $_SERVER['PHP_SELF'];?>">
Numerator: <br />
<input type = "text" name = "numOne"><br />
Denominator: <br />
<input type = "text" name = "numTwo"><br />
<input type = "submit" name = "Submit" value = "Reduce!">
</form>
<?php
//Executes task upon form submission
if (isset($_POST['Submit'])) {
$n1 = $_POST['numOne'];
$n2 = $_POST['numTwo'];
//Defines numerator simplification function
function simplifynum ($n1,$n2) {
$n1 = $_POST['numOne'];
$n2 = $_POST['numTwo'];
if ($n1 < $n2){
//Loops until numerator and denominator are reduced to simplest form
for ($x = 2;$x < $n2;$x++){
$divedn1 = ($n1/$x);
$divedn2 = ($n2/$x);
//If all divided values are purely digits (i.e. are whole numbers) and not equal to zero, sets new numerator and denominators variables to the divided value
if (ctype_digit($divedn1) && ctype_digit($divedn2) && ($divedn1 != 0) && ($divedn2 != 0)) {
$n1 = $divedn1;
$n2 = $divedn2;
}
}
//returns numerator data
return $n1;
}
}
//Defines denominator simplification function
function simplifyden ($n1,$n2) {
$n1 = $_POST['numOne'];
$n2 = $_POST['numTwo'];
if ($n1 < $n2){
//Loops until numerator and denominator are reduced to simplest form
for ($x = 2;$x < $n2;$x++){
$divedn1 = ($n1/$x);
$divedn2 = ($n2/$x);
//If all divided values are purely digits (i.e. are whole numbers) and not equal to zero, sets new numerator and denominators variables to the divided value
if (ctype_digit($divedn1) && ctype_digit($divedn2) && ($divedn1 != 0) && ($divedn2 != 0)) {
$n1 = $divedn1;
$n2 = $divedn2;
}
}
//returns denominator data
return $n2;
}
}
?>
<!-- Runs functions and reads respective values -->
<p><?php echo simplifynum($n1, $n2);?><br /> ━<br /><?php echo simplifyden($n1, $n2);?></p>
<?php
//Unsets form submission
unset($_POST['Submit']);
}
?>
</body>
爲什麼分數的每個組件的功能? –
'ctype_digit'函數需要一個字符串。傳遞一個整數假定這是單個字符的ascii數字。 [手冊](http://php.net/manual/en/function.ctype-digit.php#refsect1-function.ctype-digit-notes)在「註釋」部分說明了這一點。在你的情況下,你可以使用[is_int](https://php.net/is_int)來檢查你是否有一個整數,或者你可以跳過除法和整數檢查使用模數運算符'%'返回部門的其餘部分。所以'25%5 = 0'因爲25可以被5和26%5 = 1'平分。當可以整除時,你會得到零。 –