gpt4 book ai didi

c++ - 我有一个浮点溢出问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:01:30 26 4
gpt4 key购买 nike

好吧,我是初学者,这是我计算机科学专业的一年。我正在尝试做我教科书中的一个练习,让我使用一个名为 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;
}

这是我收到的输出:

TitleDirector2009901000000.001000000.00TerminatorJames Cameron1984120-92559631349317830000000000000000000000000000000000000000000000.00-92559631349317830000000000000000000000000000000000000000000000.00Press any key to continue . . .

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

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

感谢您对我的帮助。对不起我的长问题。这是我关于 SO 的第一篇文章,所以任何关于正确的发帖问题格式的反馈都会很棒,谢谢!

最佳答案

感谢您发布完整代码,问题现在很明显了。以下函数是问题所在:

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

您省略了以下语句:

    production_cost = p;
first_year_revenue = f;

如果没有这些语句,production_costfirst_year_revenue 在使用上述构造函数时不会被初始化。

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

关于c++ - 我有一个浮点溢出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1659155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com