-5

我正在制作一个程序来评估某物的价值。我有一个变量保存要添加的总值,rcoverE. 当我为第二个问题测试“y”时,它可以工作,但是当我输入“n”时,它无论如何都会增加 5。为什么会这样?

    #include <iostream>
    using namespace std;

    int main(){
        int year, yearE, rcoverE;
        string rcover, func;
        cout << "Enter the decade your thing was produced (eg. 20):";
        cin >> year;
        cout << "Does you typewriter have original thingy? (y,n):";
        cin >> rcover;

        rcoverE = 0;
        if(rcover == "y" || "Y"){
           rcoverE = rcoverE + 5;
        }else{
            rcoverE = rcoverE + 0;
        }
        cout << rcoverE;
        yearE = 100 - year / 2;

    }   
4

2 回答 2

3
if(rcover == "y" || "Y"){

这个条件是错误的应该是:

if(rcover == "y" || rcover == "Y"){

This:if(rcover == "y" || "Y"){逻辑上等价于if(rcover == "y" || "Y" != 0)并且"Y" !=0 始终为真。

于 2013-07-18T15:58:30.457 回答
0
if(rcover == "y" || "Y")

不评估您认为的方式。这实际上评估为 if ("rcover == 'y') 或 if('Y')",而不是 "rcover == ('y' || 'Y')。在某些语言中,编译器不允许您这样做,但在 C++ 中,只需放入语句“Y”即可返回 true。您需要将语句更改为:

if(rcover == "y" || rcover == "Y")
于 2013-07-18T16:03:34.593 回答