如何像普通数学一样划分

how to divided like normal math?

本文关键字:一样 划分 何像普      更新时间:2023-10-16

// 代码的开始

// 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,我也不知道该怎么做。

这是因为amountquantity都是整数,所以你会得到整数除法。将amount乘以 1.0 go 使其成为浮点数(更准确地说是double),并获得浮点运算。

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

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