【问题标题】:How can I print the result from this code with four places after the decimal point?如何打印此代码中小数点后四位的结果?
【发布时间】:2021-09-26 19:53:46
【问题描述】:

如何打印小数点后四位的结果?

#include <iostream>
#include <math.h>

using namespace std;

int main() {
    double A;
    double R;
    cin >> R;
    A = 3.14159 * R * R;
    cout << "A=" << A << "\n";

    return 0;
}

【问题讨论】:

标签: c++


【解决方案1】:
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;

int main() {

    double A;
    double R;
    cin >> R;
    A = 3.14159*R*R;
    cout << "A="<< fixed << setprecision(4) << A<< "\n";

    return 0;
}

添加库iomanip。在这种情况下,使用 fixed 和 setprecision 来实现打印最多 4 个小数点的目标。

【讨论】:

  • 作为初学者,我应该以哪种方式学习格式化输出?
  • 如果 C++ 版本在这里。
【解决方案2】:

请考虑以下方法。许多人会告诉你,避免使用using namespace std;。可以在here

找到很好的解释
#include <iostream>
#include <math.h>

int main(){

    double A;
    double R;
    char buffer[50] = {};    // Create a buffer of enough size to hold the output chars

    std::cout << "Enter a number >> "; std::cin >> R;
    A = 3.141519*R*R;
    sprintf(buffer, "A = %.4f\n", A);    // Here you define the precision you asked for
    std::cout << buffer;

    return 0;

}

输出在哪里:

输入一个数字 >> 56

A = 9851.8036

你可以运行它here

【讨论】:

  • C++ 初学者不需要学习 两种 方法来格式化输出。学习一个是一项艰巨的任务。
  • 这是 C 风格而不是现代 C++ 格式。
  • n. 1.8e9-where's-my-share m
  • 作为初学者,我应该以哪种方式学习格式化输出?
  • @ShantoIslamDhrubo 首先学习如何使用 iostreams 和 &lt;&lt;,因为这是 C++ 中最流行的格式化方式。 printf and friends 是从 C 继承下来的方法,也用的比较多。还有一个新方法std::format,这是最简单的,但是很新,还没有得到很好的支持。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
相关资源
最近更新 更多