help with program

Write a program that will caclulate
average of 3 numbers
(Do not change this program, just add code in place of ...)


#include <iostream>


int
main()
{
// prototypes:

float add_and_div(float, float,
float);

// variables:

float x, y, z;
float
result;

cout << "Enter three floats: ";
cin >> x
>> y >> z;

// continue the program here

here is my rendition of this program:


#include <iostream>
#define EXIT_SUCCESS 0

int main()
{
float add_and_div(float, float, float);
float x, y, z;
float result;
cout << "Enter three floats: ";
cin >> x >> y >> z;
result = add_and_div( x, y, z );
cout << endl << "Average is " << result;
return EXIT_SUCCESS;
}
float add_and_div(float n1, float n2, float n3)
{
return ( n1 + n2 + n3 ) / 3;
}

i get the following errors:

error C2065: 'cout' : undeclared identifier
error C2065: 'cin' : undeclared identifier
error C2065: 'cout' : undeclared identifier
error C2065: 'endl' : undeclared identifier
to fix those errors, just add using namespace std;:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream> 
#define EXIT_SUCCESS 0 

using namespace std;

int main() 
{ 
float add_and_div(float, float, float); 
float x, y, z; 
float result; 
cout << "Enter three floats: "; 
cin >> x >> y >> z; 
result = add_and_div( x, y, z ); 
cout << endl << "Average is " << result; 
return EXIT_SUCCESS; 
} 
float add_and_div(float n1, float n2, float n3) 
{ 
return ( n1 + n2 + n3 ) / 3; 
}
You must Prefix the std elements with the (::) scope resolution operator, for example:

1
2
std::cout
std::endl

there are other ways however to access the elements of the std.
you could do this outside of the main() function:

1
2
using std::cout;
using std::endl;

- by declaring exactly which elements from the std namespace you want local to your program, you're able to access them directly without prefixing them during the life of your program.

You could also employ the "using" directive as mentioned by Niven:

using namespace std;
Last edited on
Topic archived. No new replies allowed.