Victor Martins Victor Martins - 2 months ago 18
C++ Question

Why Am I getting a zero instead?

I'm a bit new to C++ and I'm making this small program to calculate the gross total of movies tickets.

#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;


}


At the very end, there is where the program its suppose to display the total? I thought the Arithmetic was correct however I don't understand Why it continuously displays a zero? What could I be doing wrong?
It works if I don't create a variable for the Arithmetic "grossTotal" but I have to do further formatting with "setprecision" and "fixed" function.

Answer

The code in main doesn't change grossTotal.

The declaration

double grossTotal = (aPrice * adultTick) + (cPrice * childTick);

… creates a variable grossTotal with a specified initial value. It does not declare a relationship between the values of these variables.

At the time the initializer expression (to the right of =) is evaluated adultTick and childTick are zero, because as namespace scope variables they have been zero-initialized.