2017-09-25 51 views
-3

我一直在做這個家庭作業一段時間,準備把我的頭髮拉出來。將十進制舍入到十分之一,但在C++中顯示百分之一

我需要幫助四捨五入到十分之一的位置,同時仍然在百位顯示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; 

任何想法?

+1

歡迎堆棧溢出。請花時間瀏覽[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)上的內容,瞭解什麼和你怎麼能問這裏。發佈[mcve]特別重要。 –

+0

請輸入密碼。並告訴我們您是否想要將變量本身四捨五入或者如果您想圍繞顯示屏。 – Christophe

+0

這裏明顯的選擇是實現你自己的舍入函數.... – xyious

回答

0

閱讀@ asterite的回答here

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

注意round功能只適用,如果你#include <cmath>

更新: 修改文件math.h與CMATH,感謝@ user4581301

+0

無論出於何種原因,即使在包含數學庫後圓也不起作用。 – Clueless

+0

它適用於我,提示100爲vel,10爲sec,我得到4.50,這是4.47四捨五入到十分之一,然後是0.如果我誤解了某些東西,請告訴我。 – Neb

+0

我不知道爲什麼,但它聲稱輪不是'std'的成員並且找不到標識符。 – Clueless