如何划分正常的数学?

时间:2015-02-02 00:54:04

标签: c++

/////////////////////////////////     //代码的开头

// 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;

我需要做一些像这样的价格= 2,数量= 7,金额= 12. 12/7 = 1.71428571,1.714 * 2 = 3.42857143

但我得到2作为我的答案,而不是3.42857143,我不知道保持小数。然后我必须舍入到3.43,我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

那是因为amountquantity都是整数,所以你得到整数除法。 将amount乘以1.0将其设为浮点(double更精确),并获得浮点算术。

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

确保cost的类型为double,而不是int