LoginSignup
0
0

More than 5 years have passed since last update.

制御文 (五週目の学習)

Last updated at Posted at 2018-10-19

モチベーションも大事だと思うので覚書として使用します。

五週目の感想
五週目は、if-case-for-goto等の条件分岐の学習をしました。
case 型 変数 when (cast)条件式:の発見が一番の気付きでした。
caseは引き出しのあるただのケースのイメージからケースバイケース等
色々な具体例を示すケースとして進化したと思いました。

Linqやガード節の事も知り、プログラミングの奥深さを感じました。

               

制御文

if

if(対象<=基準){} else if( ){} else{}

コード例(ガード節重要 ||重要)

参考問題文.7:TechPjin
参考解答:teratail
    class AndAnd1
    {
        static void Main(string[] args)
        {
            int realScore = 75;


            if (realScore > 100 || realScore < 0)// 先にありえない値を弾く事で、else ifの条件式を省く
                Console.WriteLine("試験の得点が正しく入力されていません。");

            else if (realScore >= 65)// 変動しない値は定義しなくても良さそうなので直入力
                Console.WriteLine("おめでとうございます。合格です。");

            else// 65,55,125それぞれの境界の値で正常動作
                Console.WriteLine("残念です。不合格です。");
        }
    }

コード例(ユーザ入力で変動的 &&より&)

    class If02
    {
        public static void Main(string[] args)
        {
            Console.Write("所持金はいくらですか");
            string stMoney = Console.ReadLine();
            int ntMoney = Int32.Parse(stMoney);

            Console.Write("単価はいくらですか");
            String stPrice = Console.ReadLine();
            int ntPrice = Int32.Parse(stPrice);

            Console.Write("何個買いますか");
            String stNumber = Console.ReadLine();
            int ntNumber = Int32.Parse(stNumber);

            int total = ntPrice * ntNumber;

            if (ntMoney < total)
            {
                Console.WriteLine("所持金が足りません");
            }
            else
            {
                int ntOturi = ntMoney - total;
                Console.WriteLine($"所持金は{ntOturi}円残っています");
            }
        }
    }
//実行結果
//所持金はいくらですか500
//単価はいくらですか108
//何個買いますか4
//所持金は68円残っています

とにかくネストを深くしない(&&||等でまとめる,
ガード節(処理の対象外を早めに return や continue/break で抜ける)
肯定形(!=より==,||はあり)

switch

switch(){case1:文break; default}

コード例(基本的なMenu,ユーザ入力,case)
    class Switch
    {
        public static void Main()
        {
            Console.WriteLine("━━━━ Menu ━━━━");// Menu作成
            Console.WriteLine("1:ファイル");
            Console.WriteLine("2:編集");
            Console.WriteLine("3:表示");
            Console.WriteLine("0:終了");
            Console.WriteLine("━━━━━━━━━━━");// Menu最後

            Console.Write("\n選択 ");// ユーザ入力
            string strAns = Console.ReadLine();
            int ans = Int16.Parse(strAns);// ユーザ入力最後
       //int でなく string のまま、case "0"としても良い。defaultが文字対応する。


            switch (ans)// Switch文
            {
                case 0:
                    Console.WriteLine("終了しますか");
                    break;
                case 1:
                    Console.WriteLine("ファイルを選択しますか");
                    break;
                case 2:
                    Console.WriteLine("編集を選択しますか");
                    break;
                case 3:
                    Console.WriteLine("表示しますか");
                    break;
                default:
                    Console.WriteLine("入力ミスです");
                    break;// Switch文最後
            }
        }
    }

コード例(C#7から値は型宣言もOK、複数渡して最初の一致ブロック実行される)

端的に言うとグーチョキパー同時出しで、適切なパターンを自動判別して出してくれる
        class Switch2
        {
            public static void Main()
            {
                PrintData(0);
                PrintData(2);
                PrintData(5);
                PrintData(false);
                PrintData(true);
                PrintData(55.5);
            }

            private static void PrintData(object obj)
            {
                switch (obj)
                {
                    case 0:
                    case 5:
                    case true:
                        Console.WriteLine($"you passed {obj}");// 0,5,trueを渡した時最初の一致ブロックが実行される
                        break;
                    case int number:
                        Console.WriteLine($"you passed a numeric value");
                        break;
                    case bool b:
                        Console.WriteLine($"you passed a boolean value");
                        break;
                    default:
                        Console.WriteLine($"Invalid data");
                        break;
                }
            }
        }
    }

}

コード例(ufcpp 問題3:平方根)
平方数かそうでないか(TrueかFalse)なので型比較(intかdouble)しました。
調べてC#7のcase式のwhenにてcastと併用できました。
case 型 変数 when (cast)条件式:
問題文、本来の解答、自作解答
        class Switch3
        {
            public static void Main()
            {
                Console.WriteLine("数値を入力してください\n");
                double x = Double.Parse(Console.ReadLine());

                x = (double)Math.Sqrt(x);
                //Console.WriteLine("{0:#.#}", x);


                switch (x)
                {
                    case double n when (int)n != x:

                        Console.WriteLine("平方数ではありません");
                        break;

                    default:
                        Console.WriteLine("平方数です");
                        break;
                }

            }
        }

ifと違いswitchする分処理早い
型指定パターンマッチング(case 型 変数 when (cast)条件式:),
範囲指定パターンマッチング(case int n when n >= 100:)

フォールスルー(fall through)

FallThrough

int value = x; …②
switch (value) {
case 0:
case 1:
System.out.println(1);
break;
default:
System.out.println(-1);
break;
}


上記の場合、

②のxが0か1なら
出力1

forループ

for(int i=0; i<5; i++),foreach(初期化子 in 配列名やList、Dictionaryなどのコレクションの要素){

コード例(基本)
for(int i=0; i<5; i++)
//初期化子;抜けるまで続ける条件;反復する際の付加 int i=0宣言、i(5)<5で抜け。反復は実行後追加して戻る
   Console.WriteLine("something");



コード例(配列)

// 通常のfor文(初期化子;条件式;反復子)

            char[] myArray = {'H','e','l','l','o'};// Hello五文字が格納01234

            for(int i = 0; i < myArray.Length; i++)
       // 変数の宣言にiが小さい内は続ける条件。ループ後毎回1追加。
       // 最初はi=0について、5より小さいのでループ;この時実行文[i]は0で'H'
            // 反復子i++により1追加されて次の実行文[i]は1で'e'
            // 条件文i(0~4)<myArray.Length(5)になるまで実行され続け4文字目'o'
            // 反復子i++により1追加されてiは5となるので条件式を抜ける
            {
                Console.WriteLine(myArray[i]);
            }



// foreach文(初期化子イン配列名)
            char[] myArray = {'H','e','l','l','o'};

            foreach(char ch in myArray)
            // 英語:for each A in B.意味:Bそれぞれ(毎に)をAに実行/格納.
       // この場合myArrayそれぞれをchに格納 H e l l o
            {
                Console.WriteLine(ch);
            }

// Output
H
e
l
l
o

コード例(Continue)
//①continue(時点で再び)する

for (int i = 0; i < 10; i++) {
    if(i == 0) {
        continue;// breakだと終了
    }

    DoSomeThingWith(i);
}


//②i<=10まで続けるがif(i<9)までcontinueなので結果9と10のみ

class ContinueTest
{
    static void Main()
    {
        for (int i = 1; i <= 10; i++)
        {
            if (i < 9)
            {
                continue;
            }
            Console.WriteLine(i);
        }

        // Keep the console open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/*
Output:
9
10
*/

//③余りが0(割り切れる)数値だけcontinueなので結果1 3 5 7 9(割り切れない)

  for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
      continue;
    }
    textBox1.Text += Convert.ToString(i) + " ";
  }

配列等のコレクションに向いてる。Linq

whileループ

bool式 while(trueか条件式)trueか条件式入るまで∞ループ

コード例(弾く事で省く &&より||)

// while(true)if {(条件)continue/break} elseif... で∞ループ

while (true)
{
    if(条件) continue;

    // 処理
}

// 具体例

int count = 0;

while (true)
{
    ++count;

    if (count == 5)
    {
        count += 5;
        continue;
    }
    else if (count >= 10) break;

    Debug.Log(count);
}


//while do

        {
            int i = 0;
            do {
                i++;
                MessageBox.Show (i.ToString ());
            } while (i <= 3);
        }

メニューに∞ループ使える

goto

goto ラベル名 ~ ラベル名:処理 ;

コード例

  for (int i=0; i < 10; i++) {
    int j = 0;
    while (true) {
      textBox1.Text += string.Format("({0:d},{1:d}) ",i,j);
      if (i * j == 25) goto EXITLOOP;
      j++;
      if (12 < j) break;
    }
  }

  EXITLOOP: ;
  textBox1.Text += "\r\nComplete";

保守性悪い、宗教上使わない人が多い、switchで対応

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