-2

Why this code isn't working as expected?

When I start debugging proizvod is always on 1, bat it should be

 0.75 = 1 - (1/4) and so on.

My code is this

#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain()
{   
    int plusminus = 1, brojac = 0;
    double proizvod = 1; 
    double pi;
    while (brojac < 6)
    {
        plusminus = plusminus + 2;
        if (brojac % 2 == 0)
        {
            proizvod = proizvod - ( 1 / plusminus );
        }
        else
        {
            proizvod = proizvod + ( 1 / plusminus );
        }
        pi = proizvod * 4;
        brojac++;
    }
    cout << "Broj PI sa 6 decimala je " << pi << "  ." << endl;
}
Jay Rajput
  • 1,813
  • 17
  • 23
DoktorD96
  • 21
  • 1
  • 7

1 Answers1

1

1 / plusminus can only be 0 because plusminus is an integer > 1 (you increment it by 2 at the start) so you're experiencing integer division.

Example of fix: 1.0 / plusminus

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219