switch 语句未执行

switch statement is not executing

本文关键字:执行 语句 switch      更新时间:2023-10-16

我有一个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;
            }
        }
    }
}
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;
}

显然您的变量tthh的值与 1 或 2 不同。要找出值是什么,请在带有 print 语句的 switch 语句中添加一个 default 子句并打印出其值。

您的案例陈述写得不正确。您可以取出开关并将其设为 if else 或 if else if。现在它正在寻找 tthh 到 == 1 ||阿拉伯数字

你打开tthh,测试它是 1 的情况,然后测试它是否小于或等于 3(显然是这样)。

然后你测试用例 2,并测试它是否大于或等于 4,它不能 b(自 2 < 4 以来)。

所以基本上,你的开关做任何事情的唯一情况是如果 tthh == 1。

我会完全删除开关,因为我似乎没有添加任何东西。

这个 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;
        }
}