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.

3 Replies

westfw (author)2008-09-18
  • 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! */

Select as Best AnswerUndo Best Answer

gmoon (author)westfw2008-09-19
Another option is "type casting," to ensure the constants are handled as floats:
float fract1 = (float) 4 / (float) 3;

Select as Best AnswerUndo Best Answer

puffyfluff (author)gmoon2008-09-19

Thanks. That helped me a lot.

Select as Best AnswerUndo Best Answer