2016-09-16 21 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