switch语句未按预期执行

时间:2018-11-30 20:06:00

标签: c++

输入输入以获得正确的总额。任何帮助将不胜感激,谢谢。

    #include <iostream>

    using namespace std;

    int main()
    {
        float cost2 = 0;
        char ch;

        cout << "1. Water \t\tRs.10" << endl;
        cout << "2. Cola \t\tRs.20" << endl;
        cout << "3. Lemonade \t\tRs.15" << endl;
        cout << "Enter your choice: " << endl;

        cin >> ch;
        switch(ch) {
        case 1: {
            cost2 += 10; // trying to add 10 if input (ch) is 1
            break;
        }
        case 2: {
            cost2 += 20;
            break;
        }
        case 3: {
            cost2 += 15;
            break;
        }
    }
    cout << "The total before tax is: Rs." << cost2 << endl;
}

2 个答案:

答案 0 :(得分:1)

更改:

df.to_csv(filename, encoding = "utf-8")

收件人:

case 1: {

,并且在所有情况下都执行相同的操作,因为case '1': { 变量的类型为ch。因此,您应该将其与字符进行比较。当您说char时,您可以想象它像说case 1,这没有任何意义。在这种情况下,您希望if(ch == 1)获得预期的结果。与switch语句相同。

答案 1 :(得分:0)

#include <iostream>

    using namespace std;

    int main()
    {
        float cost2 = 0;
        char ch;

        cout << "1. Water \t\tRs.10" << endl;
        cout << "2. Cola \t\tRs.20" << endl;
        cout << "3. Lemonade \t\tRs.15" << endl;
        cout << "Enter your choice: " << endl;

        cin >> ch;
        cout<< ch<<endl;
        switch(ch) {
        case '1': {
            cost2 += 10; // trying to add 10 if input (ch) is 1
            break;
        }
        case '2': {
            cost2 += 20;
            break;
        }
        case '3': {
            cost2 += 15;
            break;
        }

    }
    cout << "The total before tax is: Rs." << cost2 << endl;
}