Can't even manage this simple average function.

I don't know why but this doesn't work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
#include <string>

using namespace std;

int main() 
{
double a;
double b;
double avg(double a,double b) 
{
	double average = (double a + double b) / 2;
	return average;
}



cout << "Type a number. ";
cin >> a;
cout << "Type another number. ";
cin >> b;
cout << "The average of your chosen numbers is " << avg(a, b) << endl;
return 0;
}


The errors I get are

1>c:\users\asma\documents\visual studio 2010\projects\learning\learning\main.cpp(11): error C2601: 'avg' : local function definitions are illegal
1> c:\users\asma\documents\visual studio 2010\projects\learning\learning\main.cpp(7): this line contains a '{' which has not yet been matched
1>c:\users\asma\documents\visual studio 2010\projects\learning\learning\main.cpp(12): error C2146: syntax error : missing ')' before identifier 'a'
1>c:\users\asma\documents\visual studio 2010\projects\learning\learning\main.cpp(12): error C2062: type 'double' unexpected
1>c:\users\asma\documents\visual studio 2010\projects\learning\learning\main.cpp(12): error C2059: syntax error : ')'
you can't make a local function inside another function

1
2
3
4
5
6
7
8
9
double avg(double a, double b)
{
        // body
}

int main()
{
       // ...
}


and also - double average = (double a + double b) / 2;
don't use those doubles in the brackets, you have already declared variables a and b
Last edited on
Topic archived. No new replies allowed.