[英]Rounding to second decimal place unless the number is whole c++
我正在嘗試將Cpp中的平均值打印為float
2個小數點。 avg
是float
, sum
是float
, count
是int
。
目前,如果我有10/1例如,它將輸出10.00。 我希望輸出僅為10。例如,如果avg
獲得值3.1467665
,則應將其顯示為3.14
。
avg = sum/count;
std::cout << std::fixed << std::setprecision(2) << avg;
四舍五入應僅用於輸出。 無需更改avg
但如果更簡單,則可以更改其值。
尋找在c ++ 11之前使用標准的解決方案。
UPD :當我希望輸出為27.5時,輸出為27.50。
您可以根據avg
值的浮動模數選擇精度。 以下作品:
int main() {
double sum = 10;
double count = 3;
double avg = sum/count;
double mod;
std::cout << std::fixed
<< std::setprecision((modf(avg, &mod) != 0.0) ? 2 : 0)
<< avg
<< std::endl;
}
考慮增加的規格:
這是使用@IInspectable的建議方法的可能實現:
std::stringstream ss;
ss << std::fixed << avg;
size_t pos = ss.str().find('.');
if (pos + 2 < ss.str().size()) // If there is a '.' and more than 2 digits after it
pos += 3;
std::string s = ss.str().substr(0, pos); // Leave only two digits
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return ch != '0'; }).base(), s.end()); // Remove trailing zeros
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return ch != '.'; }).base(), s.end()); // Remove trailing '.' when needed
std::cout << s << std::endl;
這將輸出:
10/4 -> 2.5
10/3 -> 3.33
10/2 -> 5
10/7 -> 1.42
3.9999 -> 3.99
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.