Recommand · September 4, 2021 0

Finding Average of two numbers C++

This question already has answers here:

Printing the correct number of decimal points with cout

(12 answers)

Closed 2 hours ago.

As a newbie in the world of programming, I have to write a bit of C++ code to find the average of two numbers.
However, my code somehow appears to be incorrect. Please take a look at my code:

#include <iostream>
using namespace std;

int main() {
  float a, b, average; 

  cin >> a;
  cin >> b;

  average = (a+b)/2;

  cout << average << endl;
}

however, it says I am wrong because when I input 10 10 it outputs 10 but the system wants me to output 10.00

You need to use some I/O manipulators.
std::setprecision and std::fixed

Example:

#include <iomanip>
#include <iostream>

int main() {
    if(float a, b; std::cin >> a >> b) {
        float average = (a+b)/2;

        std::cout << std::fixed << std::setprecision(2) << average << '\n';
    }
}

Like others have said you need to change your cout line to:

cout << fixed << setprecision(2) << average << endl;

Remember that with the <<s you’re putting a stream of data (an iostream) into cout. The first piece of data is std::fixed which says "Display floats to a fixed number of decimal places, don’t cut off any trailing zeros." And then std::setprecision(2) says "Make that fixed number of decimal places 2." You could use an int variable or another number in place of 2 if you wanted. From there the stream has your average and an endline like before.

Set decimal precision
Sets the decimal precision to be used to format floating-point values on output operations.

#include <iostream>
using namespace std;
#include <iomanip>      // std::setprecision

int main() {
  float a, b, average; 

  cin >> a;
  cin >> b;

  average = (a+b)/2;

  cout << fixed << setprecision(2) << average << endl;
}