round() problem

Hi there
I want to solve this problem
mealprice=12.00
tip=20
tax=8
they're given as input I should calculate the totalcost this way:
tip=12*20/100=2.4
tax=12*8/100=0.96
totalcost=mealprice+tip+tax=12+2.4+0.96=15.36
round(totalcost)=15

by the way I should use the precise values in calculation

this code doesn't work for this testcase ,mealprice=10.25,tip=17,tax=5
I expect 13 and it shows 12
what's wrong with my code????

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
  
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    double mealprice=0;
    int totalcost=0;
    int meal=0;
    int tax=0;
    int tip=0;
      cin>>mealprice>>tax>>tip;
      meal=trunc(mealprice);
      tip=meal*tip/100;
      tip=round(tip);
      tax=meal*tax/100;
      tax=round(tax);
      mealprice=meal+tip+tax+0.5;
      totalcost=floor(mealprice+0.5);
      cout<<"The total meal cost is "<< totalcost <<" dollars.";
    return 0;
}
One problem is that you use integers insteas of float.
Second problem is using trunc and round when you are not supposed to do.

Try this code:
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
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main () 
{
  double mealprice = 0;
  double totalcost = 0;
  double meal = 0;
  double tax = 0;
  double tip = 0;

  // get input

  cout << "Meal: ";
  cin >> mealprice;
  cin.ignore (255, '\n');
  cout <<"Tax: "; 
  cin >> tax;
  cin.ignore (255, '\n'); 
  cout << "Tip: ";
  cin >> tip;

  // process input

  meal = trunc (mealprice);
  tip = meal * tip / 100;
  tax = meal * tax / 100;
  totalcost = meal + tax + tip;

  // show results

  cout << "The total meal cost is " << totalcost << " dollars.\n";
  totalcost = round (totalcost);
  cout << "The total meal cost (rounded) is " << totalcost << " dollars.\n\n";

  system ("pause");
  return 0;
}


Output:
1
2
3
4
5
Meal: 12
Tax: 8
Tip: 20
The total meal cost is 15.36 dollars.
The total meal cost (rounded) is 15 dollars.


1
2
3
4
5
Meal: 10.25
Tax: 5
Tip: 17
The total meal cost is 12.2 dollars.
The total meal cost (rounded) is 12 dollars. // WHY SHOULD IT BE 13 ?? 
thank you so much
I just convert int to double and it works
:))
You are very welcome. :)
Topic archived. No new replies allowed.