Search code examples
c++variable-declaration

How to add variable inside the cout?


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;

Solution

  • 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.