1

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

QuantumPi
  • 119
  • 3

3 Answers3

5

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';
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
2

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.

TooZni
  • 101
  • 3
  • 2
    Good explanation. Though, "_putting a stream of data (an iosteam) into cout_" is a bit confusing. `cout` is an `ostream` (not an `iostream`) and the data is not a stream. Other than that, good. +1 from me. – Ted Lyngmo Sep 03 '21 at 20:28
1

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;
}
Hossein
  • 439
  • 3
  • 9