This is a question about the c language switch statement's private rule calculation program!!

Asked 2 years ago, Updated 2 years ago, 36 views

void calculate(); int main(void) { calculate(); return 0; } void calculate() { char option; int num1, num2;

while (1) {
    printf("+ - * / Select one: ");
    scanf("%c", &option);
    getchar();
    switch (option) {
    case'+':
        printf ("Enter two values: ");
        scanf("%d %d", &num1, &num2);
        getchar();
        printf("%d + %d = %d\n", num1, num2, num1 + num2);
        break;
    case'-':
        printf ("Enter two values: ");
        scanf("%d %d", &num1, &num2);
        getchar();
        printf("%d - %d = %d\n", num1, num2, num1 - num2);
        break;
    case'*':
        printf ("Enter two values: ");
        scanf("%d %d", &num1, &num2);
        getchar();
        printf("%d x %d = %d\n", num1, num2, num1 * num2);
        break;
    case'/':
        printf ("Enter two values: ");
        scanf("%d %d", &num1, &num2);
        getchar();
        printf("%d / %d = %d (volume output)\n", num1, num2, num1 / num2);
        break;
    default:
        printf("Please re-enter!!!!\n");
        continue;
    }
    break;
}

} Run this code to printf("+ - * /"); This sentence was executed, so I purposely put it in like 509595959595959595959 Contrary to expectations,

c

2022-09-22 18:52

1 Answers

You're having the same problem as your superiors!

This problem is caused by scanf() causing misplaced values to remain in the input stream continuously and flutter. To solve the problem, you can empty the input stream properly.

It's a very annoying bug when you first encounter it.

Among the codes, printf("Please re-enter!!!!Add a line while(getchar()!='\n') {} under \n";, and empty the input stream and it will work as you intended!

Of course, my method is just an example, and there are many other good ways X3


2022-09-22 18:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.