Output wont show with the function

When I call the function cost, it just prints out to 0.
The program runs but I just need help solving this.
------------------------------------------------------------------

#include<iostream>
#include<iomanip>

using namespace std;

int main()
{
int price;
int quantity;
int amount;
double cost;

cout << "What is the given price? $";
cin >> price;

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

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

cost = static_cast<double> (price / quantity * amount);

cout << amount << " of the products cost $" << cost << endl;

system("pause");

return 0;
}
Last edited on
cost = static_cast<double> (price / quantity * amount);
If quantity > price then result is zero: you are performing integer division here.
would I have to replace the division with modulus?
closed account (E0p9LyTq)
You are being affected by integer division. You are casting to double after you have divided two int variables.

Change all the int variables to double, you don't need the static_cast then.

Or change all your variables to float, you don't need the precision double provides.

What is the given price? $2
For how many items? 5
How many would you like to purchase? 18
18 of the products cost $7.2
Last edited on
Its the way we were asked to complete the program. Without using any other variables or without changing the type of them.

Let's say I use $2 for the price, 7 for the quantity and 12 for the amount I would want to purchase. Doing the problem that's suppuse to be assigned to cost comes out to 3.42857. I have to print that out then afterwards just make it print with two decimal points.
closed account (E0p9LyTq)
Since you can't change the variable type you need to cast before you divide either price or quantity, or both.

Something like this:

cost = (static_cast<double> (price) / static_cast<double> (quantity) * (amount));
Last edited on
I tried that before I saw your reply. Thank you for the help, really appreciate it!
Topic archived. No new replies allowed.