我是C++的新手,我正在编写这个小程序来计算电影票的总票数。
#include<iostream>
#include<string>
#include<iomanip>
#include<cmath>
using namespace std;
int adultTick, childTick;
const int aPrice = 14;
const int cPrice = 10;
float rate() {
const double RATE = .20;
return RATE;
}
double grossTotal = (aPrice * adultTick) + (cPrice * childTick);
int main() {
cout << "Box Office Earnings Calculator ....\n" << endl;
cout << "Please Enter the Name of the Movie: ";
string movie_name;
getline(cin, movie_name);
cout << endl << " \" \" " << "adult tickets sold: ";
cin >> adultTick;
cout << " \" \" " << "child tickets sold: ";
cin >> childTick;
cout << endl << setw(10) << left << "Movie Title: " << setw(20) << right << " \" " << movie_name << " \" " << endl;
cout << setw(10) << left << "Adult Tickets Sold: " << setw(20) << right << adultTick << endl;
cout << setw(10) << left << "Child Tickets Sold: " << setw(20) << right << childTick << endl;
cout << setw(10) << left << "Gross Box Office Profit: " << setw(20) << right << "$ " << grossTotal;
}在最后,程序应该在哪里显示总数?我认为算术是正确的,但是我不明白为什么它一直显示为零?我能做错什么呢?如果我没有为算术"grossTotal“创建一个变量,但我必须使用"setprecision”和"fixed“函数进行进一步的格式化,那么它就可以工作。
发布于 2016-09-25 10:13:59
main中的代码不会更改grossTotal。
该声明
double grossTotal = (aPrice * adultTick) + (cPrice * childTick);…创建具有指定初始值的变量grossTotal。它不声明这些变量的值之间的关系。
在计算初始化器表达式(位于=右侧)时,adultTick和childTick为零,因为作为名称空间作用域变量,它们已被零初始化。
发布于 2016-09-25 10:16:12
int adultTick, childTick;所显示的代码在全局范围内声明了这些变量,并且这些变量被零初始化。
double grossTotal = (aPrice * adultTick) + (cPrice * childTick);所显示的代码还在全局范围内声明了此变量,并且计算公式的计算结果为0,因此此变量将被设置为0。
cout << setw(10) << left << "Gross Box Office Profit: " << setw(20) << right << "$ " << grossTotal;main()中的这一行显示了grossTotal变量的值,当然是0。
确实,在这一行之前,main()中的前面代码设置了adultTick和childTick。这没有任何区别,因为grossTotal的值已经被初始化了。
您需要更改代码,以便main()在设置这些其他变量后计算grossTotal的值。
https://stackoverflow.com/questions/39682743
复制相似问题