There are several problems in your code, but for now I'll focus on the '
if
' statements:
1. '
if
' statements can take any of these forms:
if ()
; if ()
a = b; if ()
{ a = b;
c = d;
}
2. for any of these forms, you can choose to append an '
else
' statement. '
else
' statements follow the exact same syntax as '
if
' statements:
if ()
; else
; if ()
; else
a = d; if ()
; else
{ a = d;
c = b;
}
3. As OG pointed out in solution 1, you can nest '
if
' statements within an '
if
' or '
else
' statement. If you choose to do that, it helps if you use the syntax of the last form (i. e. surrounding '
{}
'):
if ()
c = d; else
{
if ()
c = a; else
c = b; }
You can choose to omit the surrounding '
{}
' in that last example, because there is only one statement (the '
if
' and following '
else
' statement only count as one), but with the brackets it's a little easier to see where each '
else
' belongs to.
4. Regarding your code, that second
if
statement looks a little odd: There is one command and two command blocks following the
if
, but since the
if
statement ends after that first command, the two following blocks are executed unconditionally. However, it's clear that these blocks must not be executed always; the
if
or
else
conditions are missing. You have to look at the command and the two blocks after the
if
statement and decide which if them are to be executed under what condition. Then add the corresponding condition (or
else
) before each command or block.
5. As a more general advice, I suggest separating the conditional pricing from the discount. There is no need to test all combinations of age and group size - you can treat them separately and store the result of your testing in local variables (e. g. base_price based on age, and discount based on group size). Once you know the correct base price and discount, you can do the calculation and output and don't need to repeat variants all over your code. Here's a simpified version:
float base_price;
if (a <= 5)
base_price = 0.0;
else
{
if (a <= 10)
base_price = 10.0;
else
base_price = 20.0;
}
float discount = 0.0;
if (b >= 10)
discount = 0.2;
float fee = base_price * b * (1.0 - discount);
cout << "admission fee = $" << fee << endl;