【问题标题】:What is the purpose of the setprecision() used in this C++ program?这个 C++ 程序中使用的 setprecision() 的目的是什么?
【发布时间】:2023-02-10 10:04:04
【问题描述】:

创建此示例程序的唯一目的是展示 setprecision 和 setw 的作用。我不明白第三行“setprecision(5)”的用途。我评论了这条线以查看差异,但它看起来完全一样。没有目的吗?

 cout << "\nSales Figures\n";
 cout << "-------------\n";
 cout << setprecision(5);
 cout << "Day 1: " << setw(8) << day1 << endl;
 cout << "Day 2: " << setw(8) << day2 << endl;
 cout << "Day 3: " << setw(8) << day3 << endl;
 cout << "Total: " << setw(8) << total << endl;

【问题讨论】:

  • 尝试将值更改为 cout &lt;&lt; setprecision(2);cout &lt;&lt; setprecision(10);
  • 另请阅读本文档并查看示例程序:https://en.cppreference.com/w/cpp/io/manip/setprecision
  • 你的变量是浮点数,对吧?精度不影响整数。
  • 什么是day1?什么是day2?什么是day3?什么是totalminimal reproducible example 会有所帮助。
  • 感谢你们 !!我没有意识到程序要求每天的销售额,所以我只是输入整数而不是浮点数。

标签: c++ formatting iomanip


【解决方案1】:

setprecision() 函数是 iomanip 库的一部分,当您需要将浮点数输出到某个小数点时使用。这对于显示金额和其他通常以小数点后一定数量的数字显示的内容(即使这些数字为 0)非常有用。假设您有一个名为 price 的浮点数。如果您将 10.0 存储在该浮点数中,则当您打印到屏幕上时,C++ 将不知道要输出多少个小数点。 setprecision(2) 将使输出为 10.00。

您可以在此链接中找到文档:https://cplusplus.com/reference/iomanip/setprecision/

它包含以下代码作为 setprecision() 工作原理的示例。

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

int main () {
  double f =3.14159;
  std::cout << std::setprecision(5) << f << '
'; // This outputs 3.1415
  std::cout << std::setprecision(9) << f << '
'; // This outputs 3.14159
  std::cout << std::fixed; 
  std::cout << std::setprecision(5) << f << '
'; // This outputs 3.14159
  std::cout << std::setprecision(9) << f << '
'; // This outputs 3.141590000
  return 0;
}

setprecision() 仅适用于带小数点的数据类型,如浮点数和双精度数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多