可能的重复:
如何在 switch 语句中选择值范围? https://stackoverflow.com/questions/9432226/how-do-i-select-a-range-of-values-in-a-switch-statement
我遇到了一些错误,我已经搜索了一段时间,但我不知道错误的原因是什么。 (我对编程还很陌生。)
以下是我收到的错误:
error: 'Essais' cannot appear in a constant-expression| (line 200)
warning: overflow in implicit constant conversion| (line 202)
我有箱子和科特迪瓦:
char AfficherCote (int Essais)
{
char Cote;
switch (Essais)
{
(line200) case Essais<=20:
{
(line 202) Cote='Excellent';
return (Cote);
break;
}
case Essais<=40:
{
Cote='Très bon';
return (Cote);
break;
}
case Essais<=60:
{
Cote='Bon';
return (Cote);
break;
}
case Essais<=80:
{
Cote='Moyen';
return (Cote);
break;
}
case Essais<=100:
{
Cote='Muvais';
return (Cote);
break;
}
case Essais>=100:
{
Cote='Très mauvais';
return (Cote);
}
}
}
switch-case
only works with constant values(*) (such as 3
or 'a'
), not with ranges (such as <=100
). You also must not include the variable name in the case
statement. Correct syntax would be as follows:
switch (Essais)
{
case 1:
/* ... */
break;
case 2:
/* ... */
break;
default:
/* ... */
}
如果您需要范围测试,请使用if
代替switch-case
:
if (Essais <= 80)
return "Cote";
else if (Essais <= 100)
return "Muvais";
另请注意,不能使用单引号'
对于字符串。使用双引号"
相反,并使用类型的变量std::string
(not char
) 来存储字符串。
(*) To be precise, the condition given in the case
statements must be a constant expression of integral type, enumeration type, or class type convertible to integer or enumeration type (see §6.4.2/2 of the C++ Standard for details).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)