0

I wrote this code by mistake.

I know it should be 2*i instead of 2i, naturally, but compiler does not give any error messages. What is the reason?

double getpi(int terms){
  int i;
  double answer = 0;
  for(i = 1; i <= terms; i++){
    if (i % 2 == 1){
      answer = answer + (4.0/(2i - 1));
    }else{
      answer = answer - (4.0/(2i - 1));
    } 
    
  }
  return answer;
}

I tried to check that values with debugger, but it confuses me more. The value of answer is 0.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Hasoo Eun
  • 11
  • 1
  • which compiler are you using? – phuclv Oct 23 '20 at 03:01
  • does this answer your question https://stackoverflow.com/questions/33549444/what-does-the-integer-suffix-j-mean – whoami Oct 23 '20 at 03:02
  • 1
    Does this answer your question? [What does the integer suffix J mean?](https://stackoverflow.com/questions/33549444/what-does-the-integer-suffix-j-mean) – whoami Oct 23 '20 at 03:03

1 Answers1

4

Your 2i is being interpreted as a complex constant.

The fact that this compiles tells me that you are using GCC. If you compile with more warnings enabled (-Wall -Wextra -pedantic), you'll get the warning that "imaginary constants are a GNU extension".

From the GCC doc:

To write a constant with a complex data type, use the suffix ‘i’ or ‘j’ (either one; they are equivalent).

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128