Chase Rac
Chase Rac

Reputation: 23

C++ nested if statments, basic currency exchange

I have a simple C++ issue with my if statements, the program runs the values as the initial if parameters rather than performing the else if. Also I tried to code so that if the result of the function equaled 1 it would type out a grammatically correct statement is there a better way of doing that other than using another if statement?

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";
}

Upvotes: 1

Views: 653

Answers (1)

Christopher Miller
Christopher Miller

Reputation: 3451

When you type if (currency == "yen" || "y"), you probably want it to mean "if currency is equal to "yen" or if it is equal to "y", do something".

However, this is not what your if-statement actually does. The if-statement

if (currency == "yen" || "y")

first tests if the string currency is equal to "yen", and if not, it evaluates "y" by itself and checks if it is equal to true.

In this case, "y" will be truncated to a bool, meaning that it will evaluate to true (because "y" is not equal to 0). As a result, your first if-statement will always evaluate to true!

To fix this, replace your if-statement with if (currency == "yen" || currency == "y").


For your second question, you could use a conditional operator, which works as so:

cout << "You have " << (val1 == 1 ? "thing" : "things") << endl;

The conditional in this case is (val1 == 1 ? "thing" : "things"). It checks if val1 == 1, then returns "thing" if it is true and "things" otherwise.

Upvotes: 4

Related Questions