Program not giving proper mathematical answer.

Here is the actual Question

https://imgur.com/a/G6MrskV

This is what I did.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
 #include <iostream>
#include <iomanip>
using namespace std;

int main()
{
	int a;
	double b;
	cout << "Enter Distance: ";
	cin >> a;

		if (a <= 100)
		{
			b = a * 5;
		}
		else if (a > 100)
		{
			a = a - 100;
			b = (5 * 100) + (a * 8);
		}
		else if (a > 500)
		{
			a = a - 500;
			b = (5 * 100) + (8 * 400) + (a * 10);
		}
		else if (a > 1000)
		{
			a = a - 1000;
			b = (5 * 100) + (8 * 400) + (10 * 500) + (a * 12);
		}

	cout << "Cost = $" << fixed << setprecision(2) << b << endl;
	cout << endl;
	system("pause");


	return 0;
}



Now, I am getting accurate outcomes for numbers within 500.. but when I enter a number above 500, I don't get an accurate answer, and I don't know why.. This is what I am getting when I enter 501

https://imgur.com/a/J6wc326
( Enter Distance: 501
Cost: $3708.00 )
It should have been 3710 but I don't know why is it showing 3708...

Similarly, when I entered 1001

https://imgur.com/a/g4QEZPP
(Enter Distance: 1001
Cost: $7708.00 )
This again is wrong answer and far from accurate one...

However, my answer is always accurate if it is within 500 range... Can someone tell me what's the problem with my code? :/ Thanks a lot!

Do you realize that you will never get to the (a > 1000) if() statement?

Oh damn! Sorry for posting this question, this was such a basic error and I spent around 60-120 mins and still couldn't figure it out, wow! :/
Thanks a lot though for pointing it out. :| I just need to use && function there :(
Last edited on
Or just reverse the if/else if chain. With the <= 100 just a simple else.

you mean,

if (a <=100)

else if (a <=500)

else if (a <= 1000)
else


Yeah, that too could work! :D thank you ^_^
(This thread can be closed now.. Problem has been solved by jlb)
No I meant:
1
2
3
4
5
6
7
8
if(a > 1000)
...
else if(a > 500)
...
else if(a > 100)
...
else
...
jib what he said and what you're saying is literally the same thing but in a different order -_-
what he said and what you're saying is literally the same thing but in a different order -_-

Similar, yes but not identical. I prefer to stick with the simpler "single" comparison operators (<, >, ==) over the slightly more complex compound operators. IMO, that makes the logic clearer.

Besides I did say "just reverse the if/else if chain", not change the logic of the program.
Last edited on
Topic archived. No new replies allowed.