dimanche 31 janvier 2021

How could I code if-statement after switch-statement in C++?

I am writing a code to calculate the toll fee literally for my class assignment in C++. The code is shown below. My problem is that I only want to perform the calculation, ie, toll = vRate * distance if it meets any of the cases. If the input is invalid, by default, it will show "Invalid input" only and no calculation is required. For instance:

if !(default), 
    toll = vRate * distance;
    cout << "RM" <<toll << endl; 

But, I understand this would not work. Hence, any ideas in amending the code to make it clear cut and straightforward? Thank you in advanced.

#include <iostream>
using namespace std;
int main()
{
    char vCode;
    double vRate; // Toll rate for the vehicle
    double toll, distance;
    
    cout << "Enter vehicle code: " << endl;
    cin >> vCode; // C-Car, B-Bus, T-Truck, M-Motorbike
    cout << "Enter the distance travelled by the vehicle (in km): " << endl;
    cin >> distance;
    
    switch(vCode)
    {
        case 'C' : cout << "vRate = 50%" << endl;
        vRate = 0.5;
        break;
        case 'B' : cout << "vRate = 85%" << endl;
        vRate = 0.85;
        break;
        case 'T' : cout << "vRate = 100%" << endl;
        vRate = 1.00;
        break;
        case 'M' : cout << "Free toll" << endl;
        vRate = 0.00;
        break;
        default  : cout << "Invalid Vehicle Code" << endl;
    }
    toll = vRate * distance;
    cout << "RM" <<toll << endl; 
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire