The problem is not with rounding the numbers, but with output.
cout << "x=" << x << " cos(y) y=" << printf("%.2f", cos(x)) << "\n";
Here you are mixing two ways to write to the standard output. Inserting a call to printf
into cout <<
will output the return value of printf
which happens to be 4
and at the same time output something as a side effect.
So two outputs are created:
- Streaming values into
cout
outputs x=0.2 cos(y) y=4
- Calling
printf
(correctly) outputs 0.98
It is possible that the two outputs are mingled with each other, creating the impression that the result was 0.984
:
x=0.2 cos(y) y= 4
^^^^
0.98
You can use both cout
and printf
, but you should not confuse the return value of printf
with the output it creates as a side effect:
cout << "x=" << x << " cos(y) y=";
printf("%.2f\n", cos(x));
should output
x=0.2 cos(y) y=0.98
See also: C++ mixing printf and cout