Why does my first if statement work, but my else if statement doesn't? Just hoping someone can see something I may be missing. When I enter in a time between 800 and 1800 the code continues fine, but when I enter in 600 it jumps to my else statement that I entered in an illegal format.
if ((time_start >= 800) && (time_start <= 1800))
{
cout << "How many minutes did your call last? ";
cin >> minutes;
cost = minutes * 0.40;
cout << setprecision(2) << fixed << cost;
system("pause");
keepgoing = false;
}
else if ((time_start < 800) && (time_start > 1800))
{
cout << "How many minutes did your call last? ";
cin >> minutes;
cost = minutes * 0.25;
cout << setprecision(2) << fixed << cost;
system("pause");
keepgoing = false;
}
else if ((time_start < 800) && (time_start > 1800))
一个数字不可能小于800且大于1800。我假设您的意思是:
else if ((time_start < 800) || (time_start > 1800))
You've got a 'logic bug' : use ||
instead of &&
in else if
. It's simply impossible for a number to be less than 800 and greater than 1800 at the same time .
As soon as I asked this question I realized my second else if statement should be an or || statement instead of &&.
change
else if ((time_start < 800) (time_start > 1800
to
else if ((time_start < 800) || (time_start > 1800
You can simplify the code to this, else statement is not needed. Store the value in coeficient variable, that's needed to be defined before
// else coef (default value)
float coef = 0.25;
if ((time_start >= 800) && (time_start <= 1800))
{
coef = 0.40; // if true
}
cout << "How many minutes did your call last? ";
cin >> minutes;
// use coef here and remove duplicate calls
cost = minutes * coef;
cout << setprecision(2) << fixed << cost;
system("pause");
keepgoing = false;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.