0

这是我迄今为止完成的一项任务的代码。

<!DOCTYPE html>
<html>
<head><title>Numbers</title></head>
<body>
<form action="index.php" method="get">
<b>Numbers</b>
<br>
<textarea rows="12" cols="25" name="result" value="result"></textarea>
<br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>

<?php
    $result=$_GET["result"];
    if (empty($_GET['result']))
        {
            echo '<p><font size="3" color="red">Field is Empty*</font></p>';
        }
    elseif (isset($_GET['result']))
        {
            $result=(explode("\n", $result));
        }

    echo "<br />";  
    echo "Total lines passed: " . count ($result);
    echo "<br />";
    echo "Total value of numbers: " .array_sum($result);

?>

我需要一个代码来回显提交到文本框中的偶数和奇数输入的总值。前任。1, 2, 3, 4, 5 被提交,偶数的总值是 6,因为 2 和 4 是偶数,奇数的总值是 9,因为 1、3 和 5 是奇数。如果用户还输入了一个无效的整数,比如说 a、b、c。我将能够回显所有提交的无效值的列表。

1
2
3
4
5
a
b
c

Total of even numbers: 6
Total of odd numbers: 9
Invalid Numbers: a b c
4

4 回答 4

2
$result = array_map('trim', $result); // to trim the whitespace in your input
$even = $odd = $invalid = array();

foreach ($result as $num) {        
    if (is_numeric($num)) {
        if ($num % 2 == 0) {
            $even[] = $num;
        } else {
            $odd[] = $num;
        }
    } else {
        $invalid[] = $num;
    }
}

echo "Total of even numbers: " . array_sum($even) . "<br />";
echo "Total of odd numbers: " . array_sum($odd) . "<br />";
echo "Invalid numbers: " . implode(' ', $invalid) . "<br />";

演示!

于 2013-10-27T08:48:51.470 回答
0

Try this:

    $evenSum=0;$oddSum=0;
    $alphaArr=array();
    foreach($result as $key){
    if(!is_nan($key)){
    if($key%2==0){
    $evenSum+=$key;
    }
    else{
    $oddSum+=$key;
    }
    }else{
   $alphaArr[]=$key;
于 2013-10-27T08:52:57.337 回答
0

试试看:

$even=array();
$odd=array();
$invalid=array();
for($i=0;$i<count($result);$i++)
{
   if(!is_numeric($result[$i])) { $invalid[]=$result[$i]; continue; }
   if($result[$i] % 2 == 0) $even[]=$result[$i];
   else $odd[]=$result[$i];
}
echo "Sum of even numbers: " . array_sum($even);
echo "Number of even numbers: " . count($even);
echo "Sum of odd numbers: " . array_sum($odd);
echo "Invalid numbers: " . implode(",",$invalid);
于 2013-10-27T08:26:57.273 回答
0
$total = array("even" => 0, "odd" => 0, "invalid" => 0);

foreach ($result as $r){
    if(intval($r) == "" && $r != 0){
        $total['invalid']++; 
    }else{
        if ($r % 2 == 0){
            $total['even'] += $r;
        }else{
            $total['odd'] += $r;
        }
    }
}

print_r($total);
于 2013-10-27T08:30:49.673 回答