首頁  >  文章  >  後端開發  >  c++中如何保留2位元小數輸出

c++中如何保留2位元小數輸出

下次还敢
下次还敢原創
2024-04-26 15:36:131194瀏覽

在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++中如何保留2位元小數輸出

如何在C 中保留兩位小數輸出?

在C 中保留兩位小數輸出有兩種方法:

#1. 使用std::fixed 和std::setprecision

此方法透過控制輸出流的格式化來實現。

<code class="cpp">#include <iostream>
#include <iomanip>

using namespace std;

int main() {
  double value = 123.456789;

  // 设置保留两位小数
  cout << fixed << setprecision(2) << value << endl;

  return 0;
}</code>

#輸出:

<code>123.46</code>

2. 使用std::to_string 和std::substr

此方法涉及將數字轉換為字串,然後提取所需的小數位數。

#include 
#include 

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn