-4

I need to make a program that calculates cos(x) and my problem is that when I use printf for example cos(0.2) is 0.98 but it comes out as 0.984 and it's not rounding to 2 numbers.

My code:

#include <iostream> 
#include <math.h>

using namespace std;

int main()
{
    float x = 0.2;
    cout << "x=" << x << " cos(y) y=" << printf("%.2f", cos(x)) << "\n";
    return 0;
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 6
    I'm not sure the return value of `printf` is meant to be put in a stream. – mkrieger1 Mar 14 '21 at 20:38
  • 2
    printf returns an integer containing the number of things it wrote, but it will mess up your printing if you use printf and cout at the same time unless you are sure the buffers are syncronised. If you do want to set the preceision in a stream you can use https://stackoverflow.com/questions/22515592/how-to-use-setprecision-in-c – Jerry Jeremiah Mar 14 '21 at 20:40
  • either do this: `printf("x=%f cos(y) y=%2f\n",x,cos(x));` or do this: `cout << "x=" << x << " cos(y) y=" << std::fixed << std::setprecision(2) << cos(x) << "\n";` – fvalasiad Mar 14 '21 at 20:52

2 Answers2

5

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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • (note that it would make more sense mathematically to just output `cos(x)=0.98` and not `cos(y) y=0.98`) – mkrieger1 Mar 14 '21 at 21:01
2

As others have said in the comments, mixing std::cout and printf does not do what you want. Instead use the stream manipulators std::fixed and std::setprecision:

#include <iomanip>  //Required for std::fixed and std::precision
#include <iostream> 
#include <cmath> //Notice corrected include, this is the C++ version of <math.h>

using namespace std;

int main()
{
    float x = 0.2f; //Initialize with a float instead of silently converting from a double to a float.
    cout << "x=" << x << " cos(y) y=" << std::fixed << std::setprecision(2) << cos(x) << "\n";
    return 0;
}
Casey
  • 10,297
  • 11
  • 59
  • 88