Yes, the "else" only attaches to the last of the "if"/"else if" constructs.
This is one possible fix but it will only print out one of the out-of-bounds ingredients.
Code:
if (a < 1)
printf("...");
else if (a > 9)
printf("...");
else if (b < 1)
printf("...");
else if (b > 9)
printf("...");
else
printf("yum!\n");
To print out all of the offending ingredients you could use a flag.
Code:
int okay = 1;
if (a < 1) {
printf("...");
okay = 0;
}
else if (a > 9) {
printf("...");
okay = 0;
}
if (b < 1) {
printf("...");
okay = 0;
}
else if (b > 9) {
printf("...");
okay = 0;
}
if (okay)
printf("yum!\n");
Or if you want to get fancy:
Code:
#include <stdio.h>
#include <stdbool.h>
typedef struct Ingredient {
const char *name;
float lower, upper;
float amount;
} Ingredient;
int main()
{
Ingredient ingred[] = {
{ "pepper", 1.5, 3.50, 0 },
{ "salt", 5.5, 13.00, 0 },
{ "garlic", 2.0, 4.00, 0 },
{ "thyme", 0.5, 1.25, 0 }
};
int len = sizeof ingred / sizeof ingred[0];
printf("Lets cook!\n");
printf("====================\n");
for (int i = 0; i < len; ++i) {
printf("Amount of %s added? ", ingred[i].name);
scanf("%f", &ingred[i].amount);
}
bool okay = true;
for (int i = 0; i < len; ++i) {
if (ingred[i].amount < ingred[i].lower) {
printf("Needs more %s\n", ingred[i].name);
okay = false;
}
else if (ingred[i].amount > ingred[i].upper) {
printf("Too much %s\n", ingred[i].name);
okay = false;
}
}
if (okay)
printf("Delicious!\n");
return 0;
}