Reputation: 37
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?
Upvotes: 2
Views: 390
Reputation: 360
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?
Upvotes: 1
Reputation:
Use std::setprecision
from #include <iomanip>
std::cout << std::setprecision (15) << getValue() << std::endl;
Upvotes: 1
Reputation: 1
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;
}
Upvotes: 0