简体   繁体   中英

Double Values Prints out as ints

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?

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?

使用来自#include <iomanip> std::setprecision #include <iomanip>

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM