1
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.

【PHP初級㉖】switch文(条件分岐)

Last updated at Posted at 2022-07-07

[問題]  (参照:http://www.cc.kyoto-su.ac.jp/~mmina/bp1/hundredKnocksPrimary.html)
整数値を入力させ、その値が1ならone、2ならtwo、3ならthree、それ以外ならothersと表示するプログラムをswicth-case文を使って作成しなさい。

コード

switch(intval(fgets(STDIN))){
    case 1:
        echo 'one';
        break;
    case 2:
        echo 'two';
        break;
    case 3:
        echo 'three';
        break;
    default:
        echo 'others';
}

↓「4」と入力

結果

others

↓間違えたところ

switch($a = intval(fgets(STDIN))){

ここでは変数に代入する必要なし。

☆switch文(条件分岐)
 switch (式){
  case 値1:
   式が値1と等しい場合の処理1;
   break;
  case 値2:
   式が値2と等しい場合の処理1;
   break;
  case 値3:
   式が値3と等しい場合の処理;
   break;
  default:
   式がいずれの値にも等しくない場合の処理;
 }

☆if文を使ってもできるが、この問題ではswitch文を使ったほうが便利。

1
0
3

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
1
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?