C ++,如果不能正常运行 [英] C++ if else if not working properly

查看:42
本文介绍了C ++,如果不能正常运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手.我试图运行一个具有两个输入的控制台应用程序.这是我的代码

I'm new to c++. I tried to run a console application which has two inputs. This is my code

#include <iostream>

#include <string>

using namespace std;

int main(){
    string ID;
    double sal_val,com;
    cout<<"Insert fruit ID"<<endl;
    cin >> ID;
    cout<<"You entered"<<ID<<endl;
    cout<<"Insert sale Value"<<endl;
    cin >> sal_val;
    cout<<"You entered"<<sal_val<<endl;

    if(ID =="A"||"a"){
        com=(sal_val*4.5)/100;          
        cout<<"Commission for Apple Rs. " <<com<<endl;}
    else if(ID =="B"||"b"){
        com=(sal_val*5)/100;
        cout<<"Commission for Banana Rs. " <<com<<endl;}
    else if(ID =="O"||"o"){
        com=(sal_val*5.5)/100;
        cout<<"Commission for Orange Rs. " <<com<<endl;}
    else if(ID =="G"||"g"){
        com=(sal_val*6)/100;
        cout<<"Commission for Grapes Rs. " <<com<<endl;}
}

运行此命令时,无论我为"ID"提供什么值,它都会为第一个if语句提供结果.每次只有这两行运行 com =(sal_val * 4.5)/100;
cout<<"Apple Rs的委员会.<< com<< endl;

When I run this no matter what value I give for the "ID" It gives the result for the first if statement. Every time only this two lines run com=(sal_val*4.5)/100;
cout<<"Commission for Apple Rs. " <<com<<endl;

感谢您的咨询.

推荐答案

如果不使用此 if(ID =="A" ||"a"){,则应编写 if(ID =="A" || ID =="a"){,因为您的陈述: if(ID =="A" ||"a"){表示如果( ID为"A" 字母"a" ))."a"的ascii大于0,这意味着它将在 if 语句中作为 true 值读取.这就是为什么您的语句等于 if(ID =="A" || true){的原因,这就是为什么只执行此语句的原因.

Instead of this if(ID =="A"||"a"){, you should write if(ID =="A"|| ID == "a"){ because your statements: if(ID =="A"||"a"){ means if (ID is "A" or the ascii of "a"). The ascii of "a" is bigger than 0, that means it will be read as true value in the if statement. That's why your statement will be equal with if(ID =="A"|| true){ which is why only this statement will be executed.

这篇关于C ++,如果不能正常运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆