Home>

Enter the charge category and number of people. When the charge category is 1, the fee is 800 yen, 2 is 1000 yen, 3
In this case, the amount is calculated as 1500 yen and multiplied by the number of people. Show prices and prices.
I wrote the same thing in the switch-case statement and asked if there was any way to omit it.

# include<stdio.h>
int main () {
    int kubun, ninzu, ryokin, kingaku;
    printf ("Please enter the category and number of people \ n");
    scanf ("% d% d",&kubun,&ninzu);
    switch (kubun) {
        case 1:
        ryokin = 800;
        kingaku = ninzu * ryokin;
        printf ("% d \ n% d", ryokin, kingaku);
        break;
        case 2:
        ryokin = 1000;
        kingaku = ninzu * ryokin;
        printf ("% d \ n% d", ryokin, kingaku);
        break;
        case 3:
        ryokin = 1500;
        kingaku = ninzu * ryokin;
        printf ("% d \ n% d", ryokin, kingaku);
        break;
    }
printf ("\ n");
return 0;
}
c
  • Answer # 1

    kingaku = ninzu * ryokin;
    printf ("% d \ n% d", ryokin, kingaku);

    Take this part after closing the switch statement.

    Addition:
    As @otn pointed out in the comments, there are different paths for the results.
    If you can guarantee that the value of kubun is one of 1, 2, or 3, the above simplification will work.

  • Answer # 2

    # include<stdio.h>
    int main () {
        int kubun, ninzu;
        printf ("Please enter the category and number of people \ n");
        scanf ("% d,% d",&kubun,&ninzu);
        const int ryokin_table [] = {800, 1000, 1500};
        if (1<= kubun&&kubun<= 3) {
            const int ryokin = ryokin_table [kubun];
            const int kingaku = ninzu * ryokin;
            printf ("% d \ n% d \ n", ryokin, kingaku);
        }
        else {
            putchar ('\ n');
        }
        return 0;
    }

    https://wandbox.org/permlink/CZFeJL10LE6KJzEq

    Are you sure?

    In the first place you shouldn't read numbers with scanf.

    Safely get numerical values ​​from standard input in C language-Qiita

  • Answer # 3

    ryokin = -1;
        switch (kubun) {
            case 1:
            ryokin = 800;
            break;
            case 2:
            ryokin = 1000;
            break;
            case 3:
            ryokin = 1500;
            break;
        }
        if (ryokin>= 0) {
            kingaku = ninzu * ryokin;
            printf ("% d \ n% d", ryokin, kingaku);
        }
        printf ("\ n");

  • Answer # 4

    First, let's create a function that only calculates and display a result.

    int main () {
        int kubun, ninzu;
        printf ("Please enter the category and number of people \ n");
        scanf ("% d,% d",&kubun,&ninzu);
        show (calc (kubun, ninzu));
    }
    int calc (...) {
      ...
    }
    void show (...) {
    }