在C 中保留兩位小數輸出有兩種方法:1. 使用std::fixed 和std::setprecision 控制輸出流格式化,如:cout << fixed << setprecision (2) << value; 2. 使用std::to_string 和std::substr 將數字轉換為字串並提取小數位數,如:string result = str.substr(0, str.find('. ') 3);
如何在C 中保留兩位小數輸出?
在C 中保留兩位小數輸出有兩種方法:
#1. 使用std::fixed 和std::setprecision
此方法透過控制輸出流的格式化來實現。
#include <iostream> #include <iomanip> using namespace std; int main() { double value = 123.456789; // 设置保留两位小数 cout << fixed << setprecision(2) << value << endl; return 0; }
#輸出:
<code>123.46</code>
2. 使用std::to_string 和std::substr
此方法涉及將數字轉換為字串,然後提取所需的小數位數。
#include <iostream> #include <string> using namespace std; int main() { double value = 123.456789; // 转换为字符串 string str = to_string(value); // 提取两位小数 string result = str.substr(0, str.find('.') + 3); cout << result << endl; return 0; }
輸出:
<code>123.46</code>
以上是c++中如何保留2位元小數輸出的詳細內容。更多資訊請關注PHP中文網其他相關文章!