我有一个C ++程序,我必须在程序中实现switch语句。出于某种原因,我不知道switch语句没有执行。整个程序如下所示:http://pastebin.com/VxXFhGkQ。
我遇到问题的程序部分如下所示,
void processCharges() // function to calculate charges
{
int charges = 0;
// switch statement cannot be applied to strings :(
if(vehicle == "C")
{
cout << "TYPE OF VEHICLE: CAR" << endl;
cout << "TIME IN: " << hh << ":" << mm << endl;
cout << "TIME OUT: " << hhout << ":" << mmout << endl;
cout << "======================================" << endl;
thh = hhout - hh;
tmm = mmout - mm;
int tthh = 0;
if(tmm > 0)
{
tthh = thh + 1;
}
else tthh = thh;
cout << "TOTAL TIME PARKED: " << tthh << endl;
switch(tthh) {
case 1:
if(tthh <= 3) {
charges = 0;
cout << "TOTAL CHARGES:$"<<charges << endl;
break;
}
case 2:
if(tthh >= 4) {
charges = tthh * 1.25;
cout << "TOTAL CHARGES:$"<<charges << endl;
break;
}
}
}
}
答案 0 :(得分:4)
switch(tthh)
{
case 1:
case 2:
case 3:
charges = 0;
cout << "TOTAL CHARGES:$"<<charges << endl;
break;
default:
charges = tthh * 1.25;
cout << "TOTAL CHARGES:$"<<charges << endl;
break;
}
答案 1 :(得分:1)
显然,您的变量tthh
具有不同于1或2的值。要找出值是什么,请在default
语句中添加switch
子句,并附带print语句并打印出来它的价值。
答案 2 :(得分:1)
您的个案陈述书写得不正确。您可以取出开关并将其设为if else或if else if。现在它正在寻找== 1 ||的tthh 2
答案 3 :(得分:0)
你打开tthh
,测试它是1的情况,然后测试它是否小于或等于3(它显然是)。
然后你测试案例2,并测试它是否大于或等于4,它不能b(因为2 < 4
)。
所以基本上,你的开关做任何事情的唯一情况是tthh == 1.
我会完全删除开关,因为我似乎没有添加任何东西。
答案 4 :(得分:0)
那个switch语句没有多大意义。见下面的评论。
switch(tthh) {
case 1:
if(tthh <= 3) { //THIS WILL ALWAYS BE TRUE BECAUSE tthh is 1 here
charges = 0;
cout << "TOTAL CHARGES:$"<<charges << endl;
break;
}
case 2:
if(tthh >= 4) { // THIS WILL NEVER BE TRUE BECAUSE tthh is 2 here
charges = tthh * 1.25;
cout << "TOTAL CHARGES:$"<<charges << endl;
break;
}
}