4
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 5 years have passed since last update.

C言語で3パターンのおみくじを作った

Last updated at Posted at 2020-05-12

はじめに

苦CでC言語の文法を一通り学んだので、演習としておみくじをいくつか作りました。
ifを使ったものとswitchを使ったものと文字列の配列を使ったものの3パターン作りました。
(追記 5/14)
main関数の型をvoidからintに変更しました。

ifを使ったおみくじ

# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <time.h>

int main(void)
{
        int num;

        printf("Press the Enter key... ");
        getchar();

        srand((unsigned int)time(NULL));

        num = rand() % 6;

        if (num == 0) {
                printf("大吉\n");
        } else if (num == 1) {
                printf("中吉\n");
        } else if (num == 2) {
                printf("小吉\n");
        } else if (num == 3) {
                printf("末吉\n");
        } else if (num == 4) {
                printf("凶\n");
        } else {
                printf("大凶\n");
        }
        return 0;
}

switchを使ったおみくじ

# include <stdio.h>
# include <stdlib.h>
# include <time.h>

int main(void)
{
        int num;

        printf("Press the Enter key... ");
        getchar();

        srand((unsigned int)time(NULL));
        num = rand() % 6;

        switch (num) {
                case 0:
                        printf("大吉\n");
                        break;
                case 1:
                        printf("中吉\n");
                        break;
                case 2:
                        printf("小吉\n");
                        break;
                case 3:
                        printf("末吉\n");
                        break;
                case 4:
                        printf("凶\n");
                        break;
                case 5:
                        printf("大凶\n");
                        break;
        }
        return 0;
}

文字列の配列を使ったおみくじ

# include <stdio.h>
# include <stdlib.h>
# include <time.h>

int main(void)
{
        char f[][8] = {"大吉", "中吉", "小吉", "末吉", "凶", "大凶"};
        int num;

        printf("Press the Enter key... ");
        getchar();

        srand((unsigned int)time(NULL));
        num = rand() % 6;

        printf("%s\n", f[num]);
        return 0;
}

以上です

4
0
2

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