在 c++ 中,使用 `std::fixed` 和 `std::setprecision` 函數(shù)(定義于 `
在C++中,如果你想在輸出時保留兩位小數(shù),你可以使用std::setprecision和std::fixed這兩個函數(shù),它們都在
cpp
#include <iostream> #include <iomanip> int main() { double num = 3.141592653589793; std::cout << std::fixed << std::setprecision(2) << num << std::endl; return 0; }
關(guān)注:愛掏網(wǎng)
在這個例子中,std::fixed設(shè)定了輸出的格式為固定的小數(shù)點(diǎn)格式,std::setprecision(2)則設(shè)定了小數(shù)點(diǎn)后保留的位數(shù)為2。這樣,輸出結(jié)果就是3.14。
另外,你還需要注意的是,雖然std::setprecision設(shè)定了小數(shù)點(diǎn)后的位數(shù),但并不會進(jìn)行四舍五入。如果你需要進(jìn)行四舍五入,可以使用std::round函數(shù),這個函數(shù)在
cpp
#include <iostream> #include <iomanip> #include <cmath> int main() { double num = 3.141592653589793; num = std::round(num * 100.0) / 100.0; std::cout << std::fixed << std::setprecision(2) << num << std::endl; return 0; }
關(guān)注:愛掏網(wǎng)
在這個例子中,我們首先把num乘以100,然后進(jìn)行四舍五入,最后再除以100,這樣就能得到保留兩位小數(shù)的結(jié)果。輸出結(jié)果仍然是3.14。
以上就是c++++如何保留兩位小數(shù)輸出的詳細(xì)內(nèi)容,更多請關(guān)注愛掏網(wǎng) - it200.com其它相關(guān)文章!
聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準(zhǔn)確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進(jìn)行處理。