-2

///////////////////////////////// // Start of your code

// Ask the user to enter the price per quantity and the amount
// she would like to purchase
cout<< "Grocerry price calculator" <<endl;

cout<< "what is the price given $";
cin>> price;

cout<<"For how many Items? ";
cin >> quantity;

cout<< "How many would you like to purchase";
cin>> amount;






// Calculate the cost for the amount the user would like to purchase

cost =( amount / quantity) * price;


cout << amount <<" of the product cost ";
cout << cost <<endl;

I need to do something like this price =2, quantity =7, amount = 12. 12/7= 1.71428571, 1.714*2 = 3.42857143

but i get 2 as my answer instead of 3.42857143 and i dont know to keep the decimal. and then i have to round up to 3.43 which i dont know how to do it either.

1 Answers1

1

That's because both amount and quantity are integers, so you get integer division. Multiply amount by 1.0 go make it floating point (double to be more precise), and get floating point arithmetics.

cost =( 1.0 * amount / quantity) * price;

Make sure that cost's type is double, not int.

Ishamael
  • 12,583
  • 4
  • 34
  • 52
  • cost is type as a double – user3020221 Feb 02 '15 at 00:59
  • Typecast to double would also work (the operands, **not** the result.) –  Feb 02 '15 at 01:01
  • @user3020221, then just add multiplication by 1.0 inside the parens, as the answer suggests, it should address your problem. – Ishamael Feb 02 '15 at 01:01
  • 1
    Multiplying by `1.0` is an obscure way to do this. You just want a conversion, so use a cast, probably `static_cast(...)`. Better yet, define your variables as `double` in the first place. – Keith Thompson Feb 02 '15 at 01:11