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

3
  • 5
    What does double vals = 3.141592654; std::cout<<vals <<"\n"; print? Commented Jul 26, 2014 at 17:19
  • 1
    Are you sure it returns a float? ISTM it is simply rounded for output. Commented Jul 26, 2014 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::<<cout<<std::setprecision(number_of_decimals); so I can show the full value of the double? Is there a way to get how many decimals a double has :P? Commented Jul 26, 2014 at 17:43

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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?
This is another task. Look here : stackoverflow.com/questions/9999221/…
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.

1 Comment

Thanks! :D YOu should also quote that this is included in <iomanip> :D Thanks ^_^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.