C++ If, If else Calcualtor Problem

Hi I have to write a program that takes 2 inputs to indicate the amount of gas used and then calculate how much that amount of gas would cost according to the chart at the top of my program.

For example if I put in 0 for the previous month and 52 for the current I'm supposed to get and answer of $29.99.

My problem lies in my output where if I put the above numbers I would always get an answer of 15.7352 no matter what I do when I change my code.
Any help would be great.


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream> 
#include <iomanip>
using namespace std;

/* RULES: 
First 10 cubic meters $15.21 minimum cost 
Next 30 cubic meters 35.85 cents per cubic meter 
Next 85 cubic meters 33.53 cents per cubic meter 
Next 165 cubic meters 30.26 cents per cubic meter
Above 290 cubic meters 27.95 cents per cubic meter
*/ 
int main()  
{ 
	int first_month;
	int second_month;
    int number; 
    double total = 15.21; 
    double price;
	double total_cost;
    cout<<"Enter your meter number from the previous month: "; 
    cin>>first_month; 
	cout<<"Enter your meter munber from the current month: ";
	cin>>second_month;

	number=second_month-first_month;

    if( number > 290 ) //is the number greater than 290
		{ 
        price = 0.2795;  //yes
		}
	else
	{   //no, the number is less than 290
		if( number < 290)  
		{
        price = 0.3026; //yes
		}
	
    else
	{ 
		if( number < 125) 
		{
        price = 0.3353; 
		}
    else
	{
		if( number < 85) 
		{
        price = 0.3026; 
		}
	else 
	{
		if (number < 40)
		{
		price = 0.2795;
				}
			}
		}
	}
}


         
    total_cost = price * number; 

    cout<<("The total price is: $ ", total_cost  ); 
	cout<<endl;
	system("pause");
    return 0; 
}  
Last edited on
Better check your calculator.

According to my calculator, 52 * 0.3026 = 15.7352
So as far as I can tell, your program is correct.

BTW, you have a logic hole if number is exactly 290.
OK Thanks ,just needed someone other than me to look it over. Also do you know where I should put my <<setprecision(2)
setprecision(2) goes before the cout of total_cost.

Perhaps someone else can explain why the following cout statement works.
I've never seen the parenthetical syntax before (but it works):
 
cout<<("The total price is: $ ", total_cost  ); 

Topic archived. No new replies allowed.