Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当使用switch语句在C中创建一个简单的计算器时,为什么我们必须在输入数字之前指定运算符?_C_Switch Statement - Fatal编程技术网

当使用switch语句在C中创建一个简单的计算器时,为什么我们必须在输入数字之前指定运算符?

当使用switch语句在C中创建一个简单的计算器时,为什么我们必须在输入数字之前指定运算符?,c,switch-statement,C,Switch Statement,案例1: 在这种情况下,程序顺利执行 案例2: printf("Enter the operation you want to carry out (+, -, /, *): "); scanf("%c", &operator); printf("Enter two numbers: "); scanf("%lf %lf", &num_1, &num_2); 在这种情况下,在我输入数字后,它直接执行程序的其余部分,并打印默认错误消息。因为,根据: 大多数转换都会丢弃初

案例1:

在这种情况下,程序顺利执行

案例2:

printf("Enter the operation you want to carry out (+, -, /, *): ");
scanf("%c", &operator);

printf("Enter two numbers: ");
scanf("%lf %lf", &num_1, &num_2);
在这种情况下,在我输入数字后,它直接执行程序的其余部分,并打印默认错误消息。

因为,根据:

大多数转换都会丢弃初始的空白字符(以下列出了例外情况)

其中一个例外是
%c

在终端中点击“回车”时输入的换行符是一个字符。当程序正在等待一个
%lf
时,它只会丢弃它,但对于
%c
它会被用作接受的输入


理想情况下,您根本不需要点击“回车”,但许多(大多数?)终端在默认情况下是行缓冲的,所以在您点击之前,不会向您的程序发送任何内容。要获得更灵活的用户界面,请使用诅咒或适当的图形界面。

请格式化您的代码。您的问题中没有switch语句,问题只是
scanf()
。尝试打印
运算符的数值,您会看到不同之处。
printf("Enter two numbers: ");
scanf("%lf %lf", &num_1, &num_2);

printf("Enter the operation you want to carry out (+, -, /, *): ");
scanf("%c", &operator);