溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

格式化浮點數(shù),C++ format有妙招

發(fā)布時間:2024-10-10 19:50:33 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

在 C++ 中,你可以使用 <iomanip> 庫中的 setprecision()setw() 函數(shù)來格式化浮點數(shù)。以下是一些示例:

  1. 設定小數(shù)點后保留的位數(shù)
#include <iostream>
#include <iomanip>

int main() {
    double num = 3.1415926;
    std::cout << std::fixed << std::setprecision(2) << num << std::endl; // 輸出 3.14
    return 0;
}

在上面的代碼中,std::fixed 表示使用固定小數(shù)點表示法,std::setprecision(2) 表示小數(shù)點后保留兩位數(shù)字。

  1. 設定字段寬度
#include <iostream>
#include <iomanip>

int main() {
    double num = 3.1415926;
    std::cout << std::setw(10) << std::setprecision(2) << num << std::endl; // 輸出 "    3.14"
    return 0;
}

在上面的代碼中,std::setw(10) 表示輸出寬度為 10 個字符,不足的字符用空格填充。

  1. 結合使用
#include <iostream>
#include <iomanip>

int main() {
    double num = 3.1415926;
    std::cout << std::setw(10) << std::setprecision(2) << std::left << num << std::endl; // 輸出 "3.14   "
    return 0;
}

在上面的代碼中,std::left 表示左對齊。

希望這些示例對你有所幫助!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

c++
AI