0

Why is it that when I store the DATA of a double value in a char array if I get the data from the char array to another double, it returns a Float value?

In this:

double vals = 3.141592654;
char xvals[sizeof(vals)];
memcpy(&xvals, &vals, sizeof(xvals));

double y;
memcpy(&y, &xvals, sizeof(xvals));
std::cout<<y<<"\n";

OUTPUT: 3.14159

c_str
  • 359
  • 1
  • 3
  • 13
  • 5
    What does `double vals = 3.141592654; std::cout< – dari Jul 26 '14 at 17:19
  • 1
    Are you sure it returns a `float`? ISTM it is simply rounded for output. – Rudy Velthuis Jul 26 '14 at 17:19
  • omg yesss x3 Thanks, I got the answers below but I think it would be for a know number of decimals... So how bout if I want to return a double value from user custom values? Unknow number of decimals in the result. If for example there are 20 decimals, how can I get the number of decimals and then use std::< – c_str Jul 26 '14 at 17:43

2 Answers2

5

It does not "return a float value" : std::cout will simply not print all those digits by default.

you can use std::setprecison (from <iomanip>) to change the number of digits to be printed :

#include <iostream>
#include <iomanip>

int main()
{
    double vals = 3.141592654;
    std::cout << vals << "\n";

    std::cout << std::setprecision(10);
    std::cout << vals;
    return 0;
}

Output:

3.14159

3.141592654

quantdev
  • 22,595
  • 5
  • 47
  • 84
  • Ohhh I got it. So if I put setprecision with a different quantity of decimals it will make it permanent fro the next double values. Ohh I understood it :D But what about if I get a division with unknown decimals and want to cout it? How could I get the number of decimals in a double? – c_str Jul 26 '14 at 17:36
  • 1
    This is another task. Look here : http://stackoverflow.com/questions/9999221/double-precision-decimal-places – quantdev Jul 26 '14 at 17:49
3

There has been no data loss or forced conversion. The default precision for cout is 6. This will give you the answer you need

std::cout<<std::setprecision(10)<<y<<"\n";

EDIT : You need to include the header <iomanip> for std::setprecision.

Pradhan
  • 15,095
  • 3
  • 39
  • 56