I am trying to write a snippet of code that solves this problem:
Suppose that overspeed and fine are double variables. Assign the value to fine as follows: If 0<overspeed<=5, the value assigned to fine is $20.00; if 5<overspeed<10, the value assigned to fine is $75.00; if 10<overspeed<=15, the value assigned to fine is $150.00; if overspeed>15, the value assigned to fine is $150.00 plus $20.00 per mile over 15.
Now, this is what i currently have:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double overspeed;
double fine=0.0;
cout<<"overspeed"<<endl;
cin>>overspeed;
if ( 0<overspeed<=5)
fine =20.00;
else if (5<overspeed<10)
fine = 75.00;
else if (10<overspeed<=15)
fine=150.00;
else if (overspeed>15)
fine = 150.00+overspeed*20;
cout<<"The overspeed is: \n"<<overspeed<<endl;
cout<<"The fine is:\n $"<<fine<<endl;
return 0;
}
It runs but regardless of the amount i put for overspeed i always get $20 as the fine. Am i completely off or just some mistake(s)?
It's a simple syntax problem say overspeed is 30. 0<30 is true, and true<=5 is true, so you choose fine=20. The correct way is ((0<overspeed) && (overspeed<=5)). For the first else if you need to check only if overspeed <=10, since obviously, if you get at this point, overspeed>5. Same for the next else if
In the given solution, the first line fails if overspeed is equal to 0 so the program then goes to the next line which assigns 75 to fine. This solution works:
if (overspeed > 15) // greater than 15
fine = 150 + overspeed * 2;
else if (overspeed > 10) // 11 to 15
fine = 150;
else if (overspeed > 5) // 6 to 10
fine = 75;
else if (overspeed >= 1) // 1 to 5
fine = 20;