错误: 整数超出范围_错误:开关数量不是C中的整数

错误: 整数超出范围

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

错误: 整数超出范围

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值