【问题标题】:Rounding decimal to tenth but showing hundredth in c++将小数四舍五入到十分位,但在 C++ 中显示百分之一
【发布时间】:2018-03-06 20:24:12
【问题描述】:

我已经为这个家庭作业做了一段时间了,现在我已经准备好拔掉头发了。

我需要帮助将浮点数四舍五入到十分位,同时仍然在百分之一处显示 0,而我似乎没有做任何事情。 即 2.47 = 2.50

#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
float MPH;
float seconds;
const float MPH2MPS = (1609.00 / 3600.00);
float a;

cout << "       Acceleration calculator" << endl;
cout << "" << endl;

cout << "Please enter the velocity in miles per hour: ";
cin >> MPH;
cout << "" << endl;

cout << "Please enter the time in secounds: ";
cin >> seconds;
cout << "" << endl;
cout << "" << endl;
cout << "" << endl;

a = MPH2MPS * ( MPH / seconds );

cout << showpoint << fixed << setprecision(2);
cout << "The acceleration required by a vehicle to reach" << endl;
cout << "" << endl;

cout << "a velocity of " << MPH << " miles per hour in " << seconds << " seconds" << endl;
cout << "" << endl;

cout << "is " << setprecision(1) << a << " meters per second" << endl;
cout << "" << endl;
cout << "" << endl;

system("pause");
return 0;

有什么想法吗?

【问题讨论】:

  • 欢迎来到 Stack Overflow。请花点时间浏览The Tour,并参考Help Center 的材料,了解您可以在这里询问什么以及如何询问。特别重要的是发一个minimal reproducible example
  • 请显示代码。并告诉我们您是要对变量本身进行舍入还是要对显示进行舍入。
  • 这里显而易见的选择是实现自己的舍入函数......
  • 您能说出您使用哪些值作为输入吗?

标签: c++ decimal iomanip


【解决方案1】:

阅读@asterite 的回答here

cout << "is " << static_cast<double>(std::round(a * 10)) / 10 << " meters per second" << endl;

注意round函数只有在你#include &lt;cmath&gt;时才有效

更新: 用 cmath 修改了 math.h,感谢@user4581301

【讨论】:

  • 无论出于何种原因,即使包含数学库,回合也无法正常工作。
  • 它对我有用,提示 100 表示 vel,10 表示 sec,我得到 4.50,即 4.47 四舍五入到第十位,然后是 0。如果我误解了什么,请告诉我.
  • 我不知道为什么,但它声称该轮不是'std'的成员并且找不到标识符。
  • 您需要包含 cmath 库。当您没有正确包含它时会显示该错误
猜你喜欢
  • 1970-01-01
  • 2011-02-19
  • 2013-02-04
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多