0

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

        }
    }
}
4

5 回答 5

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;

}
于 2013-11-07T18:35:58.833 回答
1

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

于 2013-11-07T18:32:52.597 回答
1

你的案例陈述写得不正确。您可以直接取出开关并将其设置为 if else 或 if else if。现在它正在寻找 == 1 || 2

于 2013-11-07T18:34:11.820 回答
0

You switch on tthh, test the case where it is 1, then test if it is less than or equal to 3 (which it would obviously be).

Then you test case 2, and test if it is more than or equal to 4, which it can't b (since 2 < 4).

So basically, the only case where your switch does anything at all is if tthh == 1.

I would remove the switch altogether, as i doesn't seem to add anything.

于 2013-11-07T18:36:23.257 回答
0

That switch statement doesnt make a lot of sense. See comments below.

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;
        }
}
于 2013-11-07T18:36:33.433 回答