首页 > 解决方案 > 当我尝试输入“Y”时出现错误代码,然后 if 代码不起作用并直接转到 else 并完成

问题描述

这是我的代码

cout<<"Do you have a discount?? (Y/N) :";
cin>>code;
cout<<endl;
if (code=="Y"){
    all_cost = cost - 100000;
}
else {
    all_cost = cost;
}

其余代码都可以工作,只有当代码不起作用时

标签: c++

解决方案


我复制了你的代码并添加了一个string code声明,它对我有用。

#include <iostream>
#include<string>
using namespace std;

int main(){
    cout<<"Do you have a discount?? (Y/N) :";
    string code;
    int all_cost = 0;
    int cost = 0;
    cin>>code;
    cout<<endl;
    if (code=="Y"){
        all_cost = cost - 100000;
    }else {
        all_cost = cost;
    }
    cout<<all_cost<<endl;

}

推荐阅读