问题
<form method="get" action="Index.php">
<fieldset>
<label for="powerof">Fibonacci: </label>
<input type="text" name="powerof" value="<?php echo $_GET['powerof']; ?>"/>
<input type="submit" name='Go' value="Calculate" />
</fieldset>
</form>
<?php
$message = 'The fibonacci sequence is: <br />1<br />2<br />';
$powerof = 0;
$max = 5;
$temp = $max;
if (isset($_GET['powerof'])) {
$powerof = $_GET['powerof'];
}
if ($powerof > 100) {
$powerof = 100;
$message = 'Sorry, your input was too high. I converted it to the maximum value of 100.<br />The fibonacci sequence is: <br />1<br />2<br />';
}
$i = 1;
for ($i; $i < $powerof; $i++) {
$max = $max * $temp;
}
$x = 1;
$y = 2;
$z = $x + $y;
echo($message);
while ($z < $max) {
$z = $x + $y;
echo($z . "<br />");
$x = $y;
$y = $z;
}
?>
this is my code and the issue is that if when i enter 1 into the text box rather than it just showing the 1st number within the sequence it shows the first 4 so for 2 it displays 1 2 3 5 8 13 21 34 rather than just 1 2, any ides guys???
回答1:
Your error is at this lines :
for ($i; $i < $powerof; $i++) {
$max = $max * $temp;
}
After this loop, the $max
var is equal to 5^$powerof
, which is not what you want.
Just remove this part and it should work fine.
Also change your test from
while ($z < $max) {
to
while ($z <= $max) {
if you want to include the maximum value.
回答2:
<label for="powerof">Fibonacci: </label>
<input type="text" name="powerof" value="<?php echo $_GET['powerof']; ?>"/>
<input type="submit" name='Go' value="Calculate" />
</fieldset>
</form>
<?php
$message = 'The fibonacci sequence is: <br />1<br />2<br />';
$powerof = 0;
$max = 10;
$temp = $max;
if (isset($_GET['powerof'])) {
$powerof = $_GET['powerof'];
}
if ($powerof > 100) {
$powerof = 100;
$message = 'Sorry, your input was too high. I converted it to the maximum value of 100.<br />The fibonacci sequence is: <br />1<br />2<br />';
}
$x = 0;
$y = 1;
$z = 0;
$counter = 0;
while ($counter < $powerof) {
if ($counter <= 1) {
$z = 1;
} else {
$z = $x + $y;
}
echo($z."<br />");
$x = $y;
$y = $z;
$counter++;
}
?>
this is the working version
来源:https://stackoverflow.com/questions/24043237/create-a-mechanism-to-pass-in-a-positive-integer-and-display-all-the-values-of-t