2017-04-05 191 views
-4

錯誤即時完成我的介紹編碼類的任務之一有些麻煩。我不斷收到編譯「[錯誤]‘displayBills’時,在此範圍內未聲明的錯誤。我會附上我的代碼,任何建議將不勝感激,謝謝!聲明在範圍

#include <iostream> 
#include <cstdlib> 
using namespace std; 
int main() 
{ 
int dollars; 
cout << "Please enter the whole dollar amount (no cents!). Input 0 to terminate: "; 
cin >> dollars; 
while (dollars != 0) 
    { 
    displayBills(dollars); 
    cout << "Please enter the a whole dollar amount (no cents!). Input 0 to terminate: "; 
    cin >> dollars; 
    } 
return 0; 
} 

displayBills(int dollars) 
{ 
int ones; 
int fives; 
int tens; 
int twenties; 
int temp; 

twenties = dollars/20; 
temp = dollars % 20; 
tens = temp/10; 
temp = temp % 10; 
fives = temp/5; 
ones = temp % 5; 

cout << "The dollar amount of ", dollars, " can be represented by the following monetary denominations"; 
cout << "  Twenties: " << twenties; 
cout << "  Tens: " << tens; 
cout << "  Fives: " << fives; 
cout << "  Ones: " << ones; 
} 
+0

定義/前向聲明的順序。順便說一句,不要創建很長的未初始化變量列表,以便稍後分配給他們幾行。 – LogicStuff

+0

想象一下,編譯器從上到下只讀取一次程序文本。在它看到你調用displayBills()時,它還沒有看到該函數的任何聲明或定義。您可以通過在main(...)函數定義中放置displayBills()函數定義_before_來解決問題。 –

回答

0

沒有指定向前聲明你的displayBills功能,你必須指定一個或給它的任何調用之前把你的功能。

0

在功能main,你調用函數displayBills,但編譯器不會在這一點上知道這個函數(因爲它被聲明/稍後在文件中定義)

Eithe [R放displayBills(int dollars) { ...定義你的函數main之前,或功能main之前把至少這個函數的預先聲明:

displayBills(int dollars); // Forward declaration; implementation may follow later on; 
// Tells the compiler, that function `displayBills` takes one argument of type `int`. 
// Now the compiler can check if calls to function `displayBills` have the correct number/type of arguments. 

int main() { 
    displayBills(dollars); // use of function; signature is now "known" by the compiler 
} 

displayBills(int dollars) { // definition/implementation 
    ... 
} 

BTW:有幾個問題在你的代碼,你應該照顧,例如using namespace std通常是危險的,因爲意外的名稱衝突,功能應該有明確的返回類型(或應該是void),...

0

像其他人一直在說displayBills以上主要將幫助您的問題。但也宣告displayBills名爲displayBills.h頭文件和

#ifndef DISPLAYBILLS_H_INCLUDED 
#define DISPLAYBILLS_H_INCLUDED 

displayBills(int dollars); 
#endif DISPLAYBILLS_H_INCLUDED 

那麼你可以有displayBills.cpp的CPP文件,其中將定義功能displayBills(不要忘了包括displayBills.h)

#include "displayBills.h" 

並將它從主函數下移到它自己的cpp文件。然後在你的主函數之上包含你的頭文件。

我會這樣做,因爲它可以讓您更容易地知道哪些功能在您的項目中的哪個位置,而不是干擾您的所有功能。