我对 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
为零,因为作为命名空间范围变量它们已被零初始化。
关于c++ - 为什么我得到的是零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682743/