c ++:为什么0显示为1.29571e + 261

时间:2013-10-31 08:47:55

标签: c++ visualization double-precision

我正在尝试用c ++创建我的第一堂课。我正在创建名为geometryitems.cpp的文件并执行此操作:

using namespace std;

class Point
{
    double x, y, z;
public:
    // constructor
    Point(double x, double y, double z)
        {

        }

    // copy constructor
    Point(const Point& pnt)
        {
            x = pnt.x;
            y = pnt.y;
            z = pnt.z;
        }

    void display()
        {
            cout << "Point(" << x << ", " << y << ", " << z << ")";
        }
};

然后我从另一个文件中调用它:

#include <iostream>
#include <cstdio>
#include "geometryitems.cpp"
using namespace std;

int main()
{
    // initialise object Point
    Point pnt = Point(0, 0, 0);
    cout << "Point initialisation:" << endl;
    pnt.display();

    double t = 0;
    cout << endl << t << endl;

    Point pnt2 = pnt;
    pnt2.display();

    // keep the terminal open
    getchar();

    return 0;
}

这是输出:

t显示为正常0,但其他零则是其他一些数字。我会理解,如果它们只是非常小的数字,但也有非常大的......

为什么Point中的零显示为如此奇怪的数字?有没有办法让它看起来像普通的零?

3 个答案:

答案 0 :(得分:5)

您没有将成员变量设置为构造函数中的任何值:

Point(double x, double y, double z)
{

}

你需要

Point(double x, double y, double z) : x(x), y(y), z(z) {}

这会使用constructor initialization list初始化您的数据成员xyz

您还应该删除复制构造函数。编译器合成的一个会很好。

答案 1 :(得分:2)

它是空的

Point(double x, double y, double z)
{

}

因此,Point pnt = Point(0, 0, 0);不会初始化任何内容。使用member initializer list。您还可以阅读更多相关信息here

Point(double x, double y, double z) : x(x), y(y), z(z)
{                                  //^^^^^^^^^^^^^^^^^^
                                   // Initializer list
}

该拷贝构造函数正在将未初始化的值复制到另一个对象。

答案 2 :(得分:0)

你的构造函数是错误的。成员未初始化。将其更改为:

Point(double x_, double y_, double z_)
: x(x_), y(y_), z(z_)
{
}