0

my problem is when I am trying to print a floating-point GPA in C++.

It seems like a simple issue, but I can't get it to work. Basically I have a floating point value set to 4.0 for a GPA. However, when I try to print it like this:

cout << gpa << endl;

I get the value of 4. Without the .0 on the end. However, I want the .0 to show up. I have tried setting a precision but with no luck. Any help is appreciated.

sethcarlton
  • 71
  • 1
  • 6

2 Answers2

1
    #include <iomanip>
    ...
    cout.setf(ios::fixed);                                  // use fixed-point notation
    cout.setf(ios::showpoint);                              // show decimal point
    cout.precision(1);
    ...
    cout << gpa << endl;
dmi
  • 73
  • 1
  • 7
1

You can use std::fixed in conjunction with std::setprecision

#include <iostream> // std::fixed
#include <iomanip> // std::setprecision

int main() {
  double gpa = 4.0;
  std::cout << std::fixed << std::setprecision(1) << gpa << std::endl;
  return 0;
}

// Output is 4.0
Garee
  • 1,274
  • 1
  • 11
  • 15