如何像普通数学一样划分
how to divided like normal math?
// 代码的开始
// 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,我也不知道该怎么做。
这是因为amount
和quantity
都是整数,所以你会得到整数除法。将amount
乘以 1.0 go 使其成为浮点数(更准确地说是double
),并获得浮点运算。
cost =( 1.0 * amount / quantity) * price;
确保cost
的类型是 double
,而不是 int
。
相关文章:
- 如何将输出数字划分为奇数和偶数
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 为什么在C++中对链表这样做?(像堆叠一样处理它们)
- 堆栈和队列是否像C++中的数组一样传递?
- 是否有技术原因阻止 Java 中的 final C++ 像 const 一样严格?
- C++无符号短裤的划分导致 int
- 如何在 C++ 中将数组划分为不同的数组
- 访问数据成员(本身是对象)的数据成员,就好像它们是类成员一样
- 我们可以将集合的值存储在变量中吗?就像我们可以将数组的值存储在变量中一样
- 我如何在C++像在 Python 中一样实现 f 字符串?
- 自制的上衣:看起来一样,但不完全相同
- 如何使用 redis-plus-plus 存储二进制数据,就像我想存储结构一样?@for_stack?
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 分类还是划分枚举?
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 如何将代码划分为多个.cpp文件 C++.
- 像 CPP 中的控制台一样的应用程序
- 将一系列已排序的元素划分为相邻组
- 为什么C++中没有常量引用,就像常量指针一样?
- 如何像普通数学一样划分