Indirectly setting a variable to a decimal

I wrote a script in Lua to calculate pi using an infinite equation (which worked), but when I wrote a very similar script in C++, it broke.

When I divide 1 by a value greater than 1, instead of setting f to a decimal less than 1, it just sets it to 0.

How do I force it to set f to a decimal value?

Also, I tried adding "\n" in several ways, but that seemed to break the script. Is this just because of the compiler that I'm using? (I usually don't have access to a computer so I have to use an app on my phone)

So basically this script should function if I can just fix this one thing. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main() {
    int i = 1;
    int bank = 0;
    int d = 1;
    int f;
    int pi;
    
    while (true){
        f = 1/i; //Here's the trouble
        bank = bank + f * d;
        d = d * -1;
        i = i + 2;
        pi = bank * 4;
        cout << pi;
    }    
    return 0;
}
Last edited on
closed account (E0p9LyTq)
Line 12 is working correctly. Setting an integer variable to a value less than 1 will truncate the value to zero. That is expected behavior.

You need to change your variable types for all your variables to float or double. Preferably double for the precision.
Thanks! I tried changing some of my variables to double and to float, but I didn't think to change all of them, so... yeah maybe next time I'll be smarter ;)
closed account (E0p9LyTq)
You could also "tighten up" your code on lines 13(?)-15 with different operators:

1
2
3
bank += (f * d);
d *= -1;
i += 2;
Topic archived. No new replies allowed.