我有一个浮点溢出问题

4 c++ floating-point overflow

好吧,我是初学者,这是我作为计算机科学专业的一年.我正在尝试从我的教科书中进行练习,我使用了一个名为struct的结构MovieData,它有一个构造函数,允许我在MovieData 创建结构时初始化成员变量.这是我的代码的样子:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

// struct called MovieData
struct MovieData
{
    string title;
    string director;
    unsigned year;
    unsigned running_time;
    double production_cost;
    double first_year_revenue;

    MovieData() // default constructor
    {
        title = "Title";
        director = "Director";
        year = 2009;
        running_time = 90;
        production_cost = 1000000.00;
        first_year_revenue = 1000000.00;
    }
    // Constructor with arguments:
    MovieData(string t, string d, unsigned y, unsigned r, double p, double f)
    {
        title = t;
        director = d;
        year = y;
        running_time = r;
    }
};

// function prototype:
void displayMovieData(MovieData);

// main:
int main()
{
    // declare variables:
    MovieData movie, terminator("Terminator", "James Cameron", 1984, 120, 5000000, 2000000);

    // calling displayMovieData function for movie and terminator
    // so it will display information about the movie:
    displayMovieData(movie);
    displayMovieData(terminator);

    return 0;
}

// displayMovieData function:
// It receives struct MovieData variable as
// an argument and displays that argument's
// movie information to the user.
void displayMovieData(MovieData m)
{
    cout << m.title << endl;
    cout << m.director << endl;
    cout << m.year << endl;
    cout << m.running_time << endl;
    cout << fixed << showpoint << setprecision(2);
    cout << m.production_cost << endl;
    cout << m.first_year_revenue << endl << endl;
}
Run Code Online (Sandbox Code Playgroud)

这是我收到的输出:

Title
Director
2009
90
1000000.00
1000000.00

Terminator
James Cameron
1984
120
-92559631349317830000000000000000000000000000000000000000000000.00
-92559631349317830000000000000000000000000000000000000000000000.00

Press any key to continue . . .

在Microsoft Visual C++ 2008 Express Edition上编译.

我的问题是,这是否由于双数据类型的溢出而发生?我甚至尝试使用long double,同样的事情发生.即使我使用5mil production_cost和2mil,因为first_year_revenue两个数字输出是相同的.使用我的默认构造函数正确打印出1000000.在这种情况下我使用正确的数据类型吗?我希望它是双倍的,因为它是货币数字,美元和美分.

谢谢你的帮助.抱歉,我的问题很长.这是我关于SO的第一篇文章,所以关于发布问题的正确格式的任何反馈都会很棒,谢谢!

Gre*_*ill 8

感谢您发布完整的代码,现在问题显而易见了.以下功能是问题:

MovieData(string t, string d, unsigned y, unsigned r, double p, double f)
{
    title = t;
    director = d;
    year = y;
    running_time = r;
}
Run Code Online (Sandbox Code Playgroud)

您省略了以下语句:

    production_cost = p;
    first_year_revenue = f;
Run Code Online (Sandbox Code Playgroud)

没有这些语句,production_cost并且first_year_revenue在使用上述构造函数时未初始化.

此练习强调了在Stack Overflow上发布问题时发布您正在使用的确切代码的必要性.您发布的代码的第一个版本不同,并且不包含此错误.