2016-09-16 23 views
0

我對編程非常陌生,我正在學習C++,並且遇到了一個我認爲要以某種方式嘗試的程序,並且具有多種功能,以便我能夠理解並獲得更多練習。如何找不到標識符?有人可以解釋嗎?

在短短想取5個數字的平均值的程序,這是分配的,我知道有一個更簡單的方法,但我想與製作功能和傳遞變量練習。 教授還建議我這樣做,以獲得額外的信貸。

這裏是我有。

#include<iostream> 
#include<string> 

using namespace std; 

float num1, num2, num3, num4, num5; 

float main() { 

    cout << "Basic Average Calculator" << endl; 
    cout << "Plaese Input your list of 5 numbers Please place a space after EACH number: " << endl; 
    cin >> num1 >> num2 >> num3 >> num4 >> num5; 
    cout << "Your Average is: " << average(num1, num2, num3, num4, num5); 
    return 0; 
} 

float average(float a, float b, float c, float d, float e) { 
    a = num1, num2 = b, num3 = c, num4 = d, num5 = e; 

    float total = (a + b + c + d + e)/5; 

    return total; 
} 

此代碼不工作,我不知道爲什麼被,當我鍵入它我得到了視覺工作室沒有語法錯誤,我覺得邏輯是正確的?

我得到的平均值()函數的「標識符找不到」錯誤?

可能有經驗的人,請幫助我嗎?

+1

你的編譯器會告訴你哪個* *標識符是找不到的。你所要做的就是解決這個問題。 'main()'應該返回'int',而不是'float'。 – Barry

+0

這是平均()函數,但是,我不知道如何正確識別它? –

+2

必須使用他們 –

回答

2

單次編譯:在使用之前,標識符必須是,它們被聲明爲

void f() { g(); } 
void g() {} 

是違法的。您可以使用預先聲明解決這個問題:

void g(); // note the ; 

void f() { g(); } // legal 
void g() {} 

在你的情況,main前移到averagemain之前

float average(float a, float b, float c, float d, float e); 

地方補充。

---編輯---

這行代碼看起來腥:

a = num1, num2 = b, num3 = c, num4 = d, num5 = e; 
              ^^^^^^^^ 

假設這應該是

a = num1, num2 = b, num3 = c, num4 = d, e = num5; 

則似乎沒有理由有這個函數首先參數。

你可以改變你的代碼是:

float average() 
{ 
    return (num1 + num2 + num3 + num4 + num5)/5; 
} 

int main() 
{ 
    ... 
    cout << "Your Average is: " << average(); 
    ... 
} 

float average(float a, float b, float c, float d, float e) 
{ 
    return (a + b + c + d + e)/5; 
} 

int main() 
{ 
    ... 
    cout << "Your Average is: " << average(num1, num2, num3, num4, num5); 
    ... 
} 
+0

哇!非常感謝你!它的工作,感謝您的澄清。我已經編寫了其他程序,其中的函數將在main()之後出現,並且它們仍然有效?這是一個特例嗎? –

+0

@VictorMartins也許他們是C89程序,並且/或者導致未被注意的未定義行爲 –

+0

@VictorMartins不是特例,也許你是用非標準選項編譯的。另外,請參閱我的編輯,並附上有關代碼的其他註釋。 – kfsone