0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

備忘録~詰まってしまった繰り返し処理においての疑問点

Last updated at Posted at 2022-01-08
<?php
$scores = [];

do{
    echo '点数を入力 >';
    $score = (int)trim(fgets(STDIN));
    if ($score === -1){
        break;
    }

    $scores[] = $score;
    $sum = 0;
    for ($i = 0; $i < count($scores); $i++) {
        echo $i + 1 . ':' . $scores[$i] . PHP_EOL;

        $sum += $scores[$i];
    }
    echo '合計:' . $sum . PHP_EOL;

} while(true);

/*
80=>
点数を入力 >80
1:80
合計:80

80=>
1:80
2:80
合計:160
点数を入力 >
*/

上コードは入力した値とその合計を出力する。

<?php
$scores = [];
$sum = 0;
do{
    echo '点数を入力 >';
    $score = (int)trim(fgets(STDIN));
    if ($score === -1){
        break;
    }

    $scores[] = $score;
    for ($i = 0; $i < count($scores); $i++) {
        echo $i + 1 . ':' . $scores[$i] . PHP_EOL;

        $sum += $scores[$i];
    }
    echo '合計:' . $sum . PHP_EOL;

} while(true);

/*
80=>
点数を入力 >80
1:80
合計:80

80=>
1:80
2:80
合計:240
点数を入力 >
*/

$sum = 0;の場所を変えるとうまく動作しなくなった。
=>
scoresには今まで入力した値が格納されており、合計(sum)はscoresの配列の値を足し合わせている。
つまり、sumは繰り返し処理の際に毎回0にしないと値が重複してしまう。
※①80を入力
scores =[80];
合計:80
②80を入力
scores =[80,80];
合計:80(前に残った値)+80+80=240

へんに詰まってしまった...

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?