【问题标题】:Add Decimals with Set Precision C++使用 Set Precision C++ 添加小数
【发布时间】:2015-09-17 02:14:40
【问题描述】:

我正在设计一个使用二次公式计算 2 个根的程序。我试图让我的输出语句 root1root2 将数字输出到两位小数玩家(即 2.00、5.00 等)。但是,当我使用 setprecision 命令时,它似乎不起作用。例如,当我输入三个点为 (1, -1, 2) 时,我得到的点是 (2, -1),而不是我正在寻找的 (2.00, -1.00)。

这是我的代码:

#define _USE_MATH_DEFINES // for C++
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    double pointa;
    double pointb;
    double pointc;
    double discriminant1;
    double root1;
    double root2;

    cout << "Please enter a, b and c: ";
    cin >> pointa;
    cin >> pointb;
    cin >> pointc;

    discriminant1 = pow(pointb, 2) - (4 * pointa * pointc);

    root1 = (-pointb + sqrt(discriminant1)) / (2 * pointa);
    root2 = (-pointb - sqrt(discriminant1)) / (2 * pointa);

    std::cout << "Root1: " << std::setprecision(3) << root1 << endl;
    std::cout << "Root2: " << std::setprecision(3) << root2 << endl;
    return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    通过输出std::fixed选择定点格式。

    【讨论】:

    • 你使用 std::fixed 而不是 std::cout ?
    • 链接到的文档有一些示例
    猜你喜欢
    • 2021-12-06
    • 2011-01-27
    • 2016-03-09
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 2021-04-28
    相关资源
    最近更新 更多