简体   繁体   中英

Why am I getting this error: invalid operands of types ‘int’ and ‘<unresolved overloaded function type>’ to binary ‘operator<<’

I am the definition of a beginner. I am working with C++ in my school's Linux server. I have been working at this program for a few hours and I can't figure out what I'm doing wrong. I've reassigned variables and restated my formulas but nothing works. Please help.

#include<iostream>
#include<string>
using namespace std;

const int f=5;

int main ()
{
        int a,b,c,d,e,sum,avg;
        cout << "Please enter five numbers. " << endl;
        cin >> a >> b >> c >> d >> e;
        sum= a+b+c+d+e;
        cout << "The average of those numbers is: " << endl;
        cout << avg =(sum / f) << endl ;
return 0;
}

The error states: invalid operands of types 'int' and '' to binary 'operator<<'

Basically the problem is how cout << avg =(sum / f) << endl is parsed.

<< is left associative and has higher precedence than = so the expression is parsed as

(cout << avg) = ((sum/f) << endl)

Now the right hand side of your assignment is int << endl which raises the error, since the operation makes no sense ( << it's not defined for int, decltype(endl) arguments)

Here the correct code....

#include<iostream>
#include<string>
using namespace std;

const int f=5;

int main ()
{
        int a,b,c,d,e,sum,avg;
        cout << "Please enter five numbers. " << endl;
        cin >> a >> b >> c >> d >> e;
        sum= a+b+c+d+e;
        avg =(sum / f);
        cout << "The average of those numbers is: " << endl;
        cout << avg << endl ;
return 0;
}

output:

Please enter five numbers. 
1 2 3 4 5
The average of those numbers is: 
3
    

The problem is in this statement- cout << avg =(sum / f) << endl ; either you could write

cout<<sum/f<<endl; 

or you could just-

avg=sum/f;
cout<<avg<<endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM