[英]Why Am I getting a zero instead?
我对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”函数进行进一步的格式化。
main
中的代码不会更改grossTotal
。
报关单
double grossTotal = (aPrice * adultTick) + (cPrice * childTick);
…创建具有指定初始值的变量grossTotal
。 它没有声明这些变量的值之间的关系。
在初始化器表达式( =
右边)被评估时, adultTick
和childTick
为零,因为作为命名空间范围变量,它们已被零初始化。
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
没有任何区别,因为已经对grossTotal
的值进行了初始化。
您需要更改代码,以便在设置了这些其他变量之后, main()
计算grossTotal
的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.