[英]case in a switch statement in C
#include<stdio.h>
void main(){
char operator;
double a, b;
printf("enter an operand(+,-,*,/)");
scanf("%c",&operator);
printf("enter two operands");
scanf("%lf %lf",&a,&b);
switch(operator){
case '+': printf("%lf is the output of a & b",(a+b)); break;
case '-': printf("%lf is the output of a & b",(a-b)); break;
case '*': printf("%lf is the output of a & b",(a*b)); break;
case '/': printf("%lf is the output of a & b",(a/b)); break;
}
}
I know that only an integer is allowed after a case. 我知道在个案之后只允许使用整数。 I also know that any character written inside single inverted commas writtens an ascii interger. 我也知道,在单个反引号内书写的任何字符都会写成ascii interger。
In this the argument inside the switch statement is a character, switch(operator);
在此,switch语句中的参数是一个字符switch(operator);
. 。
How will that equate with an integer inside the case? 这将如何等于案例中的整数? case '+':
The condition in the switch
-statement needs not to be type int
exactly but "any expression of integer type (char, signed or unsigned integer, or enumeration)" (cf., for example, switch statement documentation at cppreference ). switch
语句中的条件不必完全为int
类型,而是“整数类型的任何表达式(char,有符号或无符号整数或枚举)”(例如,参见cppreference的switch语句文档 )。 So using variable operator
of type char
as condition in the switch
-statement is ok. 因此,在switch
-statement中使用char
类型的变量operator
作为条件是可以的。
The constant expressions in each case:
-label are converted to the promoted type of expression ( char
in your case) and the result of evaluating the condition is then compared with the (converted) value of the expression. 在每种case:
,常量表达式case:
-label都将转换为提升的表达式类型(在您的情况下为char
),然后将条件评估的结果与表达式的(转换后的)值进行比较。 A constant expression of type char like '+'
, '-'
is therefore OK, too. 因此,也可以使用char类型的常量表达式,例如'+'
, '-'
。
In the end, the promoted type of the condition is char
, each constant in your case:
-statements is of type char
, and therefore char
is compared with char
. 最后,条件的提升类型为char
,在您的case:
,每个常量case:
-statement为char
类型,因此将char
与char
比较。
Note that the char-"value" of constant '+'
is it's 8 bit ASCII-value, which is 43
. 请注意,常量'+'
的字符“值”是8位ASCII值,即43
。 Also, if one enters +
in the console when using scanf("%c",&operator)
, the "value" of operator
will be the 8 bit ASCII-value of +
, too, ie 43
. 此外,如果一个进入+
使用时在控制台scanf("%c",&operator)
,所述的“价值” operator
将是8位ASCII值+
,也即43
。 In this case, the switch-statement will compare 8 bit 43
with 8 bit 43
... 在这种情况下,开关状态将比较8位43
和8位43
...
Hope it helps. 希望能帮助到你。
char
is just the 8 bit (mostly) integer char
只是8位(大部分是整数)
so case '+':
is an equivalent of the to case 43:
as 43 is the ascii code of '+' 所以case '+':
等同to case 43:
因为43是'+'的ASCII码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.