Meraj al Maksud
Meraj al Maksud

Reputation: 1582

Why different versions of same compiler is giving different outcomes?

I was trying to calculate nth harmonic number. Here's the main snippet of my program:

#include<cstdio>

int main(){
    int T; scanf("%d", &T);

    for (int C = 1; C <= T; C++){
        int n; scanf("%d", &n);
        long double H = 1;

        for (int i = 2; i <= n; i++)
            H += (1.0/i);

        printf("%.8lf\n", H);
    }

    return 0;
}

When I run this program on my machine (inside Code::Blocks IDE, compiler gcc 5.1), everything seems fine.

Input:

10
1
2
3
4
5
6
7
8
9
10

Output:

1.000000
1.500000
1.833333
2.083333
2.283333
2.450000
2.592857
2.717857
2.828968
2.928968

But when I run it inside an online editor, it prints zero instead. Here, the compiler is gcc 8.3.

I want to know the reason behind this phenomenon and the way to avoid this so that I can get my expected output.

Upvotes: 1

Views: 164

Answers (1)

PeterT
PeterT

Reputation: 8284

You should turn on your compiler warnings. It helps a lot with things like these. If you would have done so it would show:

warning: format '%lf' expects argument of type 'double', but argument 3 has type 'long double' [-Wformat=]
   15 |         printf("Case %d: %lf\n", C, H);
      |                          ~~^        ~
      |                            |        |
      |                            double   long double
      |                          %Lf

So this should give you a similar result in both versions:

int n; scanf("%d", &n);
long double H = 1;

for (int i = 2; i <= n; i++)
    H += (1.0/i);

printf("%.8Lf\n", H);

Upvotes: 6

Related Questions