【问题标题】:Why is my Else If 'vehicleHeight' code being ignored? [duplicate]为什么我的 Else If 'vehicleHeight' 代码被忽略? [复制]
【发布时间】:2021-01-12 22:45:12
【问题描述】:
cout << "Are you driving a vehicle onto the ferry? (y/n) ";
    cin >> vehicle;
    if (vehicle == 'y' || vehicle == 'Y') {
        cout << "What is the length of the vehicle in feet? ";
        cin >> vehicleLength;
        if (vehicleLength > 20) {
            extraLengthCharge = (vehicleLength - 20) * extraLengthPrice; }
        cout << "Is the vehicle over 7 feet high? (y/n) ";
        cin >> vehicleHeight;
        if (vehicleHeight == 'y' || 'Y') {
            vehiclePrice = 69.00, fuelSurcharge = 10.40;
        } else if (vehicleHeight == 'n' || 'N') {
            vehiclePrice = 43.00, fuelSurcharge = 4.15;
        }
    else if (vehicle == 'n' || vehicle == 'N') {
        vehiclePrice = 0, fuelSurcharge = 0; }
    }

如果响应为“是”,我的代码会给我正确的“票价”,但如果我输入“否”,它仍会分配“是”值。我认为这与我的 else if 语句格式有关 vehicleHeight。 感谢和抱歉新手问题。

【问题讨论】:

  • vehicleHeight == 'y' || 'Y' 回头看看你写的第一个 if,然后改变这个以同样的方式工作。

标签: c++ if-statement


【解决方案1】:

条件vehicleHeight == 'y' || 'Y' 和vehicleHeight == 'n' || 'N' 将始终为真,因为'Y' 和'N' 将始终为真并且与它们一起使用逻辑或。

您应该使用条件vehicleHeight == 'y' || vehicleHeight == 'Y' 和vehicleHeight == 'n' || vehicleHeight == 'N',就像您在其他if 语句中使用的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    相关资源
    最近更新 更多