c - 请解释一下这个程序到底出了什么问题,我是新手

标签 c scanf

<分区>

我正在借助开关运算符制作一个加减乘除程序。在这里,我想制作一个程序,仅当用户输入任何其他字符而不是“Y”时才会停止。问题是:当我运行程序时,在各个案例的结果之后它只打印“你想继续吗”然后程序停止。请帮忙!先感谢您! :)

#include<stdio.h>
int main() {
    int n,a,b;
    char answer;
    while(1)  {
        printf("enter \n1.Addition \n2.subtraction \n3.division \n4.multiplication\t");
        scanf("%d",&n);
        switch(n)  {
            case 1:   {
                printf("enter value of a and b:\t");
                scanf("%d %d",&a,&b);
                printf("addition of %d+%d is %d",a,b,a+b);
                goto ans;
            }
            case 2:  {
                printf("enter the value of a and b:\t");
                scanf("%d %d",&a,&b);
                printf("Subtraction of %d-%d is %d",a,b,a-b);
                goto ans;
            }
            case 3:  {
                printf("enter the value of a and b:\t");
                scanf("%d %d",&a,&b);
                printf("Division of %*% is %d",a,b,a/b);
                goto ans;
            }
            case 4:  {
                printf("enter the value of a nad b:\t");
                scanf("%d %d",&a,&b);
                printf("Multiplication of %d*%d is %d",a,b,a*b);
                goto ans;
            }
            default:  printf("invalid value!");
            goto ans;
        }
        ans:  {
            printf("Do you want to continue?(Y/N):\t");
            scanf("%c",&answer);
            if(answer=='Y')  continue;
            else  break;
        }
    }
    return 0;
}

最佳答案

代替这个

scanf("%c",&answer);

尝试使用这个:

scanf(" %c",&answer);

格式字符串中的空白会占用空白,包括换行符,并读取第一个非空白字符。

关于c - 请解释一下这个程序到底出了什么问题,我是新手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26117888/

相关文章:

c - 如何仅使用 sscanf 从字符串中提取所有数字?

c - scanf 不等待输入就返回 0

C scanf 读取 32 位整数时出错

scanf() 问题之前的 C/C++ printf()

C 读取行并对数据排序

python - numpy 中的等效函数

C Char多维数组定义

c++ - 数组索引到矩阵索引

c++ - 为什么 vkGetPhysicalDeviceMemoryProperties 会返回多个相同的内存类型?

html - 如何使用 tidy 删除所有 HTML 标签