c++ - C++嵌套if语句,基本货币兑换

标签 c++ if-statement

我的if语句有一个简单的C++问题,该程序将值作为初始if参数运行,而不是执行else if。我还尝试编码,以便如果函数的结果等于1,它将键入语法正确的语句,除了使用另一个if语句之外,还有更好的方法吗?

int main()
{
cout << "Please type out amount and currency type to convert to dollars.\n";
double val1;
string currency;
double result = 0;
cin >> val1 >> currency;
if (currency == "yen" || "y")
{
    result = val1/100;
    if (result == 1) {
        cout << "You have " << val1 << "yen which equals \n"
            << result << ", dollar.";
    }
    else
    cout << "You have " << val1 << "yen which equals \n"
        << result << ", dollars.";
}
else if (currency == "euros" || "e")
{
    result = val1*1.25;
    if (result == 1) {
        cout << "You have " << val1 << "euros which equals \n"
            << result << ", dollar.";
    }
    else
        cout << "You have " << val1 << "euros which equals \n"
        << result << ", dollars.";
}
else if (currency == "pounds" || "p")
{
    {
        result = val1 *1.2;
        if (result == 1) {
            cout << "You have " << val1 << "pounds which equals \n"
                << result << ", dollar.";
        }
        else
            cout << "You have " << val1 << "pounds which equals \n"
            << result << ", dollars.";
    }
}
else
    cout << "I didn't understand, please try again.\n";
}

最佳答案

当您键入if (currency == "yen" || "y")时,您可能希望它的意思是“如果currency等于"yen"或等于"y",请执行一些操作”。
但是,这不是您的if语句实际执行的操作。如果陈述if (currency == "yen" || "y")首先测试字符串currency是否等于"yen",否则,它自己评估"y"并检查其是否等于true。
在这种情况下,“y”将被截断为bool,这意味着它将求值为true(因为"y"不等于0)。结果,您的第一个if语句将始终评估为true!
要解决此问题,请将if语句替换为if (currency == "yen" || currency == "y")

对于第二个问题,您可以使用条件运算符,其工作方式如下:cout << "You have " << (val1 == 1 ? "thing" : "things") << endl;在这种情况下,条件是(val1 == 1 ? "thing" : "things")。它检查是否为val1 == 1,如果为"thing",则返回true,否则为"things"

关于c++ - C++嵌套if语句,基本货币兑换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62841766/

相关文章:

C++ 返回指针与使用 std::move 返回本地对象

c++ - 在 C++ 中创建自定义数据类型

javascript - 如何使用 if 与 $http.post 的数据回调?

c++ - 可以将名称作为参数传递给 C++ 模板吗?

c++ - C++ 中虚拟关键字的使用

c++ - SmartPTR实现heap->isValid断言

html - <g:if>和<g:set>在grails中的误解

c++ - 我需要在 else-if 之后加上 constexpr 吗?

algorithm - 你会如何在 Haskell 中表达它?

JavaScript if 语句改变 Div