212Views3Replies

Author Options:

Pi Problems Answered

I am trying to write a program that calculates pi. I am doing it in Visual C++. I am using the Gregory-Leibniz series. My problem is that I cannot figure out how to do the division necessary. It isn't returning decimals. For example, 4/3 returns 1, and 1/2 is returning 0. Is it even possible to get it to return decimals? I've tried using int, float and short as the answer variable and none worked.

Discussions

The forums are retiring in 2021 and are now closed for new topics and comments.
0
westfw
westfw

12 years ago

  • Make sure you use float or double for your data types.
  • Include decimal points in your constants, or C might think they're integers
  •       float fract1 = 4/3;    /* This probably results in 1.0 */      float fract2 = 4.0/3.0;   /* Try this instead! */
0
gmoon
gmoon

Reply 12 years ago

Another option is "type casting," to ensure the constants are handled as floats:
float fract1 = (float) 4 / (float) 3;
0
puffyfluff
puffyfluff

Reply 12 years ago

Thanks. That helped me a lot.