2

I am trying to use a add function to take the double value and add it with a another double value to get the answer. I use the get method/function to get the answer value. The answer value is only showing in int and not by double. Like for example, 12.0 + 10.0 is equal to 22.0 but when I display the result it only says 22. Here is the code that I am working on...

double x = 0.0;
void addValue(double value) 
{ 
  x = value + x;
}

double getValue() 
{
  return x;
}
int main()
{
  addValue(12.0);
  addValue(10.0);
  cout << getValue() << endl;
  return 0;
}

The result of this code is 22 What I am trying to get is 22.0

How can i fixed this without having to use the set precision?

Nicole
  • 37
  • 4
  • The `iomanip` header has [setprecision](http://en.cppreference.com/w/cpp/io/manip/setprecision). I can't tell if you're asking how to set the precision, or how to do it without using `setprecision`... – Jonesinator Sep 27 '17 at 03:09
  • @Jonesinator I am trying to do it without using the setprecision – Nicole Sep 27 '17 at 03:10
  • Why? That's exactly what it's for. – Jonesinator Sep 27 '17 at 03:11
  • Well I do know I can use the setprecision to add a decimal to it. Tho I want to do it without having to use the setprecision. In my other programs, I was able to print out double values without having to use the setprecision but for some reason I cannot figure out why this program will not let me do that – Nicole Sep 27 '17 at 03:15

3 Answers3

1

cout cuts off to round values if the fraction after decimal is 0. Try printing any values with real fraction values like 12.5 it will work. So if you need to print the .0 value, you need to use setprecision or use printf .

For better understanding you can follow through this question How do I print a double value with full precision using cout?

IR Emon
  • 360
  • 3
  • 14
  • 1
    It’s not `std::cout` that limits the number of digits; it’s the stream inserter (the `<<` operator). You’d see the same thing with **any** output stream: `std::ofstream out(“demo.txt”); out << 12.0 << ‘\n’; `. – Pete Becker Sep 27 '17 at 13:10
1

Use std::setprecision from #include <iomanip>

 std::cout << std::setprecision (15) << getValue() << std::endl;
0

You can use std::setprecision to set precision, but it will only keep significant (meaningful) digits to set precision. In this particular case, 0 is not significat in 22.0. So if you really want to print out 22.0, then you have to set fixed precision (set value to number you desire). Your code will be as below.

#include <iostream>
#include <iomanip>
using namespace std;

double x = 0.0;
void addValue(double value) 
{ 
  x = value + x;
}

double getValue() 
{
  return x;
}
int main()
{
  addValue(12.0);
  addValue(10.0);
  cout << fixed <<std::setprecision(1) << getValue() << endl;
  return 0;
}
fvzaur
  • 1
  • 3