关于case语句 为什么会是这样
来源:百度知道 编辑:UC知道 时间:2024/08/22 07:54:30
#include <iostream>
using namespace std;
int main()
{
int grade;
cin>>grade;
if(grade<=100)
{
switch(grade)
{
case grade<=100&&grade>90:cout<<"A\n";break;
case grade<=89&&grade>=80:cout<<"B\n";break;
case grade>=70&&grade<=79:cout<<"C\n";break;
default :cout<<"error";
}
}
return 0;
}
C:\MSDev98\MyProjects\wsd project\A.cpp(12) : error C2051: case expression not constant
C:\MSDev98\MyProjects\wsd project\A.cpp(13) : error C2051: case expression not constant
C:\MSDev98\MyProjects\wsd project\A.cpp(14) : error C2051: case expression not constant
C:\MSDev98\MyProjects\wsd project\A.cpp(16) : warning C4065: switch statement contains 'default' but no 'case' labels
执行 cl.exe 时出
using namespace std;
int main()
{
int grade;
cin>>grade;
if(grade<=100)
{
switch(grade)
{
case grade<=100&&grade>90:cout<<"A\n";break;
case grade<=89&&grade>=80:cout<<"B\n";break;
case grade>=70&&grade<=79:cout<<"C\n";break;
default :cout<<"error";
}
}
return 0;
}
C:\MSDev98\MyProjects\wsd project\A.cpp(12) : error C2051: case expression not constant
C:\MSDev98\MyProjects\wsd project\A.cpp(13) : error C2051: case expression not constant
C:\MSDev98\MyProjects\wsd project\A.cpp(14) : error C2051: case expression not constant
C:\MSDev98\MyProjects\wsd project\A.cpp(16) : warning C4065: switch statement contains 'default' but no 'case' labels
执行 cl.exe 时出
不能这样写的 在switch前面写个 if语句 断定grade的数值case后面写1 2 3 4 5 6或者 a b c d e f
你去看下书吧.
怪不得一楼让你去看书。C语言里面的switch跟VB不同,它的参数只能是整型或字符型变量,case后面只能是常量,不能是如你所写的表达式。
你可以这样写:
if(grade<=100)
{
grade/=10;
switch(grade)
{
case 10 :
case 9 :cout<<"A\n";break;
case 8 :cout<<"B\n";break;
case 7 :cout<<"C\n";break;
default :cout<<"error";
}
}
case 之后只能跟int和char型