switch 文の「定数式」の部分には整数値や文字(文字列では無い)を判定 するものしか使用できません.また,case 句は必ず「文」や break を必要とする訳でもありません.そこで,先週の月と日数の問題を switch を使用したものに変更してみましょう.break などの省略を工夫してみましょう.
13: prime number |
素数の判別は本来は自動で行うのがスマートなプログラムですが,今回はあらかじめ素数が分かっているものとして処理を考えてください.素数の自動検出はこの後 for 文のところで改めて行います.
乱数を使ってじゃんけんをシミュレートするプログラムを if 文を用いて作成しましょう.コンピュータとあなたの対戦形式風にします.手は Gu, Choki, Pa の表現として,勝ち負けあいこを以下のように表示するものとします.
You: Choki Computer: Gu Winner is Computer! |
You: Choki Computer: Pa Winner is you! |
You: Pa Computer: Pa Aiko |
勝ち負けの判定には論理演算子を使用せずに,しかも,以下の形のように処理を短くすることを考えてください.上手く剰余を利用すると実現できます.
if(hoge) hogehoge; else if(hege) hegehege; else hugehuge;
4桁の正の整数を乱数を用いて1つ発生させる.次に1,10,100のどれかの数を乱数により発生させ,その桁で四捨五入した数を表示させるプログラムを作成せよ.
Round off 5692 at the position 10 is 5700. |
以下に示すのはまったく意味の無い判別処理を1億回繰り返す際の if 文と switch 文の処理速度の違いを計測するものです.if else で一番下(21回の条件判断)の else の処理を1億回繰り返す場合と,同じような判断(完全に同じでは無いですが)を switch 文で行う場合の比較です.試してみてください.
#include <stdio.h> #include <time.h> main() { int i, num = 100000; clock_t t1, t2; t1 = clock(); for(i=1; i<=100000000; i++) if(num<=100) num = 100; else if(num<=200) num = 200; else if(num<=300) num = 300; else if(num<=400) num = 400; else if(num<=500) num = 500; else if(num<=600) num = 600; else if(num<=700) num = 700; else if(num<=800) num = 800; else if(num<=900) num = 900; else if(num<=1000) num = 1000; else if(num<=1100) num = 1100; else if(num<=1200) num = 1200; else if(num<=1300) num = 1300; else if(num<=1400) num = 1400; else if(num<=1500) num = 1500; else if(num<=1600) num = 1600; else if(num<=1700) num = 1700; else if(num<=1800) num = 1800; else if(num<=1900) num = 1900; else if(num<=2000) num = 2000; else if(num<=3000) num = 3000; else num = 100000; t2 = clock(); printf("Process time of if_else: %5.2f sec\n", (double)(t2 - t1) / CLOCKS_PER_SEC); t1 = clock(); for(i=0; i<=100000000; i++) switch(num){ case 100: num = 100; break; case 200: num = 200; break; case 300: num = 300; break; case 400: num = 400; break; case 500: num = 500; break; case 600: num = 600; break; case 700: num = 700; break; case 800: num = 800; break; case 900: num = 900; break; case 1000: num = 1000; break; case 1100: num = 1100; break; case 1200: num = 1200; break; case 1300: num = 1300; break; case 1400: num = 1400; break; case 1500: num = 1500; break; case 1600: num = 1600; break; case 1700: num = 1700; break; case 1800: num = 1800; break; case 1900: num = 1900; break; case 2000: num = 2000; break; case 3000: num = 3000; break; default: num = 100000; break; } t2 = clock(); printf("Process time of switch: %5.2f sec\n", (double)(t2 - t1) / CLOCKS_PER_SEC); return(0); } |