user182951
user182951

Reputation: 13

Different output between compilers

I am doing the first problem on Project Euler.

I have the following code:

#include <stdio.h>

int main() {
    int number;
    int sum;
    while (number < 1000) {
        if (number % 3 == 0 || number % 5 == 0) {
            sum += number;
            number++;
        }
        else {
            number++;
        }
    }
    printf("The answer is %d", sum);
    return 0;
}

When I compile this via compileonline.com, I get 233168. When I compile this in gcc I get 2686824. What causes this difference?

Upvotes: 0

Views: 68

Answers (1)

user4233758
user4233758

Reputation:

Compileonline probably initializes the variables.

You have to initialize them manually.

#include <stdio.h>

int main() {
    int number = 0;
    int sum = 0;
    while (number < 1000) {
        if (number % 3 == 0 || number % 5 == 0) {
            sum += number;
            number++;
        }
        else {
            number++;
        }
    }
    printf("The answer is %d", sum);
    return 0;
}

Upvotes: 3

Related Questions