Samit Kapoor
Samit Kapoor

Reputation: 47

Why does my code show different output on different compiler?

This is a code to calculate nth fibonacci number.

Code :

#include<stdio.h>

int main(){
    int n;
    printf("N: ");
    scanf("%d", &n);
    long double third, first = 0 , second = 1;
    for(int i=1 ; i<=n ; i++){
        third = first + second;
        first = second;
        second = third;
    }
    printf("The result is : %Lf", third);
    return 0;
}

This code shows correct output when I run it on an online compiler i.e. https://www.onlinegdb.com/online_c_compiler but when I run this on MS Visual Studio Code, it returns wrong output.

Output of https://www.onlinegdb.com/online_c_compiler :

N: 10
The result is : 89.000000

Output from MS Visual Code :

N: 10
The result is : -0.000000

I carefully checked the code I used on both the compilers was exactly same. I think the code is correct but there is some problem in my MS Visual Studio Code. What could be the reason of this unknown behavior?

Upvotes: 2

Views: 1133

Answers (1)

ClaudioDeLise
ClaudioDeLise

Reputation: 247

First of all, you should always check the return value of scanf.

#include <stdio.h>
#include <stdlib.h>

int main(){
    int n;
    printf("N: ");
    if (scanf("%d", &n) != 1) {
        fprintf(stderr, "Error in scanf");
        exit(EXIT_FAILURE);
    }
    long double third, first = 0 , second = 1;
    for (int i = 1 ; i <= n ; i++) {
        third = first + second;
        first = second;
        second = third;
    }
    printf("The result is : %Lf\n", third);
    return 0;
}

The C language standard has several areas that are implementation-defined, which means that each compiler implementation is free to choose how it will behave in those situations, and to document how it will behave. The C standard states also that the behaviour of certain statements are undefined - which means that the compiler implementers have no information about how to provide correct behaviour - since there is no definition for ‘correct’ in these cases.

Upvotes: 2

Related Questions