はじめての C
0 から 9までの間の乱数をつくるプログラムを作成せよ。
乱数の種 (seed) はキーボードから入力できるように。
- /* zeroto9 */
- #include
- #include
- main()
- {
- int seed, random;
- printf("Input seed = ");
- scanf("%d", &seed);
- srand(seed);
- random = rand() % 10;
- printf("random : %d\n", random);
- }
「ゲーム」
乱数の種 (seed) はキーボードから入力させる。
敵は 10 離れたところから 1つずつ前進してくる。
敵との距離が 0 になったところで 敗北 → ゲームは終了。
敵は 0 から 5 の 6つのコースのどこかにいる。
敵は 1つずつ進むごとにコースを 1つ変える (または静止する) ことができる。
レーダーとレーザ砲とを使えるが 一度にどちらかしか操作できない。
レーザが命中したら つぎのステージに移る。
全部で 5回戦あるが ステージが上がると敵のスピードも速くなる。
- /* game */
- #include
- #include
- main()
- {
- int seed, distance, cource, goal, round, laser, speed = 0;
- printf("Input seed = ");
- scanf("%d", &seed);
- srand(seed);
- printf("/n");
- for ( round = 1 ; round < 6 ; round++ ) {
- printf("+++ stage %d +++\n\n", round);
- cource = rand() % 6;
- speed++;
- for ( distance = 10 ; ; distance -= speed ) {
- if (distance <= 0) {
- printf("=== you lose (>_<) ===\n");
- exit(0);
- }
- if (cource == 0) {
- cource += rand() % 2;
- } else if (cource == 5) {
- cource += rand() % 2 - 1;
- } else {
- cource += rand() % 3 - 1;
- }
- printf("(current distance = %d)\n\n", distance);
- printf("select '1'(radar) or '2'(fight)\n);
- printf("Input your choice = ");
- scanf("%d", &laser);
- printf("\n");
- if (laser == 1) {
- printf("enemy cource >> %d <<\n",cource);
- } else if (laser == 2) {
- printf("select laser cource 0 - 5\n");
- printf("Input your choice = ");
- scanf("%d", &goal);
- if (goal == cource) {
- printf("\n");
- printf("=== you win ! ===\n\n");
- break;
- }
- printf("\n");
- printf("== miss the target ==\n\n");
- } else {
- printf("set '1' or '2' only\n");
- }
- }
- }
- }
main() のなかで %d と %c とを併用すると 関数 scanf() のうち scanf("%c", &lazer) のほうが お亡くなりになるみたい。
しかたなく すべて変数を int に変更しました。
text: 金山典世さん(稚内北星)のページ