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;
Blaze
  • 16,736
  • 2
  • 25
  • 44
Ravi Arya
  • 9
  • 1
  • 6

4 Answers4

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.

Blaze
  • 16,736
  • 2
  • 25
  • 44
1

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

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

MubashirEbad
  • 289
  • 1
  • 7
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);
Bhawan
  • 2,441
  • 3
  • 22
  • 47
0

C++ way would be:

float average = static_cast<float>(first + second + third) / 3.;
std::cout << average << std::endl;
carobnodrvo
  • 1,021
  • 1
  • 9
  • 32