【问题标题】:Why when I put fixed point notation, my output is 0.00?为什么当我输入定点符号时,我的输出是 0.00?
【发布时间】:2013-10-20 20:41:15
【问题描述】:

我想在我的程序中添加定点符号,但是当我这样做时,最终输出始终是 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;
}

对不起,我的英语和编程技能不好。

【问题讨论】:

  • 检查您的输入及其单位。我的测试产生了数字,它们太小了,所以总是以您要求的精度显示为 0.00。
  • @andymcevoy 是的!你是对的。我解决了,谢谢!

标签: c++ fixed point notation


【解决方案1】:

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

例如,试试cout.precision(20);

另外,你不需要在你的函数体内那些using namespace std; 语句。只需在顶部一次就足够了。

【讨论】:

  • 谢谢!问题是我所有测试输入的结果都是 0.00000000000
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-14
  • 2021-11-11
  • 1970-01-01
  • 2021-08-16
相关资源
最近更新 更多