错误: 整数超出范围
The switch statement only works with integral type of values/variables, integral types like integer, character.
switch语句仅适用于值/变量的整数类型,整数,字符等整数类型。
The error switch quantity not an integer occurs if the value/variables passed in the switch statement is not either integer or character.
如果在switch语句中传递的值/变量既不是整数也不是字符,则会发生错误切换数量不是整数的情况。
In this example, consider the statement – switch(choice) – Here, choice is a float variable i.e. we have passed a float variable in switch statement, this is the cause of error switch quantity not an integer.
在此示例中,考虑语句– switch(choice) –在这里, 选择是一个float变量,即我们在switch语句中传递了float变量,这是导致switch数量错误而不是整数的原因 。
Example:
例:
#include <stdio.h>
int main(void) {
float choice = 2.0f;
switch(choice){
case 1:
printf("Case 1\n");
break;
case 2:
printf("Case 2\n");
break;
case 3:
printf("Case 3\n");
break;
case 4:
printf("Case 4\n");
break;
default:
printf("Case default\n");
}
return 0;
}
Output
输出量
prog.c: In function ‘main’:
prog.c:7:9: error: switch quantity not an integer
switch(choice){
^~~~~~
prog.c:5:9: warning: variable ‘choice’ set but not used [-Wunused-but-set-variable]
float choice = 2.0f;
^~~~~~
How to fix?
怎么修?
Use only integral variables/values with the switch statement. In this example, we changed type of choice variable from float to int.
在switch语句中仅使用整数变量/值。 在此示例中,我们将选择变量的类型从float更改为int 。
Correct code:
正确的代码:
#include <stdio.h>
int main(void) {
int choice = 2;
switch(choice){
case 1:
printf("Case 1\n");
break;
case 2:
printf("Case 2\n");
break;
case 3:
printf("Case 3\n");
break;
case 4:
printf("Case 4\n");
break;
default:
printf("Case default\n");
}
return 0;
}
Output
输出量
Case 2
翻译自: https://www.includehelp.com/c-programs/switch-quantity-not-an-integer-error-in-c.aspx
错误: 整数超出范围