0

I want to add float average variable inside the cout. What's the perfect way for it?

int first , second , third;
cout<<"enter the first number: ";
cin>>first;
cout<<"enter the second number: ";
cin>>second;
cout<<"enter the third number: ";
cin>>third;

cout<<float average=(first+second+third)/3;
2

4 Answers 4

1

You can't do that. Just declare the variable before printing it.

float average = (first + second + third) / 3;
std::cout << average;

What you can do, however, is just not having the variable at all:

std::cout << (first + second + third)/3;

Also note that the result of (first+second+third)/3 is an int and will be truncated. You might want to change int first, second, third; to float first, second, third; if that's not your intention.

Sign up to request clarification or add additional context in comments.

Comments

1

float average=(first+second+third)/3; cout<<average OR

cout<<((first+second+third)/3)

Comments

1

You need to declare the variable type first.

You can do something like this.

int first , second , third;
cout<<"enter the first number: ";
cin>>first;
cout<<"enter the second number: ";
cin>>second;
cout<<"enter the third number: ";
cin>>third;

float average;

cout<< (average=(first+second+third)/3);

Comments

0

C++ way would be:

float average = static_cast<float>(first + second + third) / 3.;
std::cout << average << std::endl;

1 Comment

The addition may overflow, might be better to divide before addition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.