# doubt in setprecision function in C++

many times i have seen “answer should be correct to a relative error of 10^-6”.

when i used cout << setprecision(9) << val; i think it’s giving correct answer upto 9 decimal points but still i get WA and after adding cout << fixed; it gives AC!

my question is if “setprecision” is giving correct answer upto required decimal place then why do we need to print something like “6.00000000” why “6” is not accepted (as "cout << fixed; " is doing that only)?

Hi @pk301

``````float x=12/2;

cout<<fixed<<setprecision(9)<<x;

This will print 6 upto 9 decimal digits ,i.e,6.000000000 but if you will not fix it before
setprecision

then no decimal digit would be printed.``````

yaa that’s was my doubt that even if we don’t print decimal than what is wrong in that(for this case i.e. if we print 6 rather than 6.000000000)?

Output should come just as it is explained in the testcase

if 6.000000000 is test case output the 6 will be considered wrong

consider it as a string while checking both are equal or not

but there are written that “relative error” !!

“answer should be correct to a relative error of 10^-6” so you should print a number upto 6 decimal places !

setprecision(n) here the n is the total no of digits printed (without fixed)

setprecision(n) here n is the number of decimal places (with fixed)

eg.,

without fixed:-

double f =3.14159;

std::cout << std::setprecision(5) << f << ‘\n’;

std::cout << std::setprecision(9) << f << ‘\n’;

output:-

3.1416

3.14159

With fixed:-

double pi=3.14159

std::cout << std::fixed;

std::cout << std::setprecision(5) << f << ‘\n’;

std::cout << std::setprecision(9) << f << ‘\n’;

output:-

3.14159

3.141590000