setprecision call



Dear all,

if someone can find the time i would very much appreciate
help on understanding the setprecision call.
To me it seams as if it changes the data type,which is
absolute impossible but i have no understanding what
happens in the follwing code.

-----CODE------------------
#include <iostream>
#include <iomanip>

int main(int argc, char **argv)
{
float num1=0.0,num2=0.0,num3=0.0;

num1 = 8.06; num2 = 5239.0; num3 = num2/num1;

std::cout <<"num1: "<< num1 <<" "
<<"num2: "<< num2 <<" "
<<"num3: "<< num3 <<" "
<< std::endl;

std::cout << std::setprecision(8)
<< "High precision num1: "
<<num1<< std::endl;

num3 = num2/num1;

std::cout <<"num1: "<< num1 <<" "
<<"num2: "<< num2 <<" "
<<"num3: "<< num3 <<" "
<< std::endl;


return 0;
};

---------END CODE---


-----------------OUTPUT-------------------
num1: 8.06 num2: 5239 num3: 650
High precision num1: 8.0600004
num1: 8.0600004 num2: 5239 num3: 649.99994
---------------END OUTPUT----------------

Thank you very much.
TZ
To me it seams as if it changes the data type
Why you say so?
setprecision increases the number of digits shown in the stream, When the stream precision is higher than floating point accurateness the values may be a bit different
Did you read this yet?
http://cplusplus.com/reference/iostream/manipulators/setprecision/

iomanipulators change the way the data is interpreted by the stream. It doesn't have any affect on the original variable. If you are stepping in the debugger you can see that the variables aren't changing as a result of the setPrecision call even though the output is changing. I'm not sure why the num3 printed as 650 originally. I'm not sure how to find out what the default behavior is for the streams to be honest. Maybe someone else can answer that. It must be documented in the std but I don't know what the default precision is for stdout.

Once you set the precision to 8 I believe it remains set that way until you change it back so it looks like that on the final statements the precision is still set to 8. Recalculating num3 didn't change anything.
Topic archived. No new replies allowed.