2016-09-25 217 views
0

我對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」函數進行進一步格式化。

回答

2

main中的代碼不變grossTotal

聲明

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

&hellip;用指定的初始值創建一個變量grossTotal。它沒有聲明這些變量的值之間的關係。

在時間初始化表達式(至=右側)被評估adultTickchildTick是零,因爲作爲命名空間範圍變量它們已經被初始化爲零。

+0

不確定,但重點是聲明不指定關係,它只指定一個初始值。 –

1
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()adultTickchildTick前面的代碼。這並沒有什麼不同,因爲grossTotal的值已經被初始化了。

您需要更改代碼,以便main()在設置這些其他變量後計算grossTotal的值。

相關問題