You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++代码疑问:输入有效会员卡类型时仍输出else语句内容

问题原因

你的代码里的else只和最后一个if (cardType == 3)绑定,这就意味着:

  • 输入1或2时,前两个if会正确计算折扣,但第三个if条件不满足,就会触发else输出"Invalid Card"
  • 只有输入3时,第三个if成立,才不会执行else的内容
修复方案

把多个独立的if改成else if链式结构,这样else只会在所有有效卡片类型都不匹配时才执行。或者用switch语句,逻辑更清晰。

方案1:使用else if

#include <iostream>

using namespace std;

int main(void)
{
    cout << "Total Purchase Cost: Php ";
    double total;
    cin >> total;
    
    cout << "Loyalty Card Type: ";
    int cardType;
    cin >> cardType;
    double discount = 0;
    // 用const修饰常量,代码更规范
    const double type1 = 0.10;
    const double type2 = 0;
    const double type3 = 0.15;
    
    if (cardType == 1) {
        discount = total * type1;
    } else if (cardType == 2) {
        discount = total * type2;
    } else if (cardType == 3) {
        discount = total * type3;
    } else {
        cout << "Invalid Card\n";
    }
    
    cout << "Discounted Cost: Php " << discount << endl;
    
    return 0;
}

方案2:使用switch语句

#include <iostream>

using namespace std;

int main(void)
{
    cout << "Total Purchase Cost: Php ";
    double total;
    cin >> total;
    
    cout << "Loyalty Card Type: ";
    int cardType;
    cin >> cardType;
    double discount = 0;
    const double type1 = 0.10;
    const double type2 = 0;
    const double type3 = 0.15;
    
    switch(cardType) {
        case 1:
            discount = total * type1;
            break;
        case 2:
            discount = total * type2;
            break;
        case 3:
            discount = total * type3;
            break;
        default:
            cout << "Invalid Card\n";
            break;
    }
    
    cout << "Discounted Cost: Php " << discount << endl;
    
    return 0;
}
额外优化建议
  • 给折扣率加上const修饰,明确它们是不可修改的常量
  • 统一输出格式,调整换行位置避免输出混乱

内容的提问来源于stack exchange,提问作者Adrian Galvez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 19:35:30