Ask coding questions

← Back to all posts
Incorrect Math Answer

Whenever I type this C++ code segment, i get an answer of 1.32679e-06. Does anyone know why this happens, or how to make the cosine of pi divided by 2 equal zero? It's a radians measurement, not a degrees measurement.

#include <iostream>
#include <cmath>
using namespace std;

int main()
const double PI = 3.14159;

cout << "cos(PI / 2) = " << cos(PI / 2) << "\n\n";

return 0;


It happens because you're using 3.14159 instead of the actual value of pi, which is a much longer and more precise number. 1.32679e-06 is the scientific notation of 0.00000132679, which is very close to zero. The answer is correct given the double PI is not exactly equal to pi, so the cosine of (PI / 2) is not equal to zero. Try using the M_PI variable that comes with <cmath> instead of defining a variable yourself.
EDIT: You could also try rounding it.


You'll probably never get exactly 0, but you can get much closer (0.0000000000000000612323) by using M_PI as I did here.