I'm writing a simple shipping program where a package weighing a certain amount and traveling per 500 miles = cost.
For example, a package weighing 2kg traveling up to 500 miles costs $1.10
if it exceeds 500 miles then it goes up another $1.10, same for if it goes up another per 500 miles.
If you ship a package 400 miles and it weighs 2 kg, the bill should be $1.10. If you ship a package 700 miles and it weighs 2.5 kg, it should cost $4.40.
My question is, is there a way to to write the code without writing multiple if else statements
and do this:
if(weight > 20)
cout << "bad user" << endl;
else
cost = looky[(int)weight]*miles/500;
note that (int)weight is 2 for 2, 1 for 1.9 or 1.1, 0 for 0.5, etc... see how the indexing works?
this is cute, efficient, and very clean for small lists of values. For very large lists, it is not so good, for example if they allowed up to 10 tons in increments of 5... you can use loops to populate the table but at some point its just as ugly as anything else. It also works because you have continuous values from 0-20. If you had 0-10 and 15-20 with a gap, you have to get weird and need at least 1 more if statement.
If you had a huge list of categories you would probably want to revisit the ideas and figure out some clean way to do it, but it depends on the data what approach might be best.
Consider if the distance is 250 miles. Your cost will be $0.55. That's not what the problem specification is asking for.. You want to use integer arithmetic.
PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.