简体   繁体   中英

Why different versions of same compiler is giving different outcomes?

I was trying to calculate n th 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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM