c++ - 为什么当我输入定点符号时,我的输出是 0.00?

标签 c++ fixed point notation

我想在我的程序中加入定点符号,但是当我这样做时,最终输出总是 0.00

我试着把这个放在

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);

在程序的不同部分,但没有任何变化。

这是我的程序:

#include <iostream>
#include <cmath>

using namespace std;

void get_input(double& body1, double& body2, double& distance);
void get_output(double m1, double m2, double d);
double compute_GAF(double m1, double m2, double d); //takes the masses of two bodies and the distance and computes gravitational attractive force between them
const double G = 6.673 * (1/pow(10, 11)); //global constant for Gravity

int main()
{
    double m1, m2, d;
    char ans;

    do
    {

        cout << "Thanks for using the Gravitational Attractive Force Calculator\n";
        cout << endl;

        get_input(m1, m2, d);

        get_output(m1, m2, d);


        cout << "Do you want to calculate again? (Y/N)" << endl;
        cin >> ans;
        cout << endl;

    } while (ans == 'y' || ans == 'Y');

    return 0;
}

void get_input(double& body1, double& body2, double& distance)
{
    using namespace std;

    cout << "Enter the mass of the two objects with a space in between:\n";
    cin >> body1 >> body2;
    cout << "Enter the distance between the objects:\n";
    cin >> distance;
    cout << endl;

    return;
}

void get_output(double m1, double m2, double d)
{
    using namespace std;
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);

    cout << "The Gravitational Attractive Force of the two objects is " << compute_GAF(m1, m2, d);

    if (compute_GAF(m1, m2, d) == 1)
        cout << " dyne.\n";
    else
        cout << " dynes.\n";
    cout << endl;
    return;
}

double compute_GAF(double m1, double m2, double d)
{
    double F;

    F = (G*m1*m2) / pow(d, 2);

    return F;
}

对不起我糟糕的英语和糟糕的编程技巧。

最佳答案

您可能为正在计算的数字设置的精度太低(即您需要更多的小数位)。

例如,尝试使用 cout.precision(20);

此外,您不需要在函数体内使用那些 using namespace std; 语句。在顶部一次就足够了。

关于c++ - 为什么当我输入定点符号时,我的输出是 0.00?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482627/

相关文章:

c++ - array_view.synchronize_asynch 会等待 parallel_for_each 完成吗?

html - 固定 div 的右侧溢出其父级

android - 使用JS替换固定位置

python - 点云与python中另一个点云的最佳拟合

c++ - 为什么我只能在 Ubuntu 的 G++ 中获得垃圾值?

c++ - 使用指针初始化数组,然后从中读回数据。

java - 在 2 个角点之间生成随机位置

HTML 数字输入删除小数点?

c++ - Accelerated C++ exercise 8-5 解不清楚

jquery - 当页面内点击内容较少时修复页脚