Reputation: 473
I just started C and wanted to try out a euler problem.
For Euler #2
#include <stdio.h>
int main(){
int sum;
int prev = 0;
int curr = 1;
int next;
do{
if(curr % 2 == 0 ){
sum = sum + curr;
}
next = curr + prev;
prev = curr;
curr = next;
} while (curr <= 4000000);
printf("%d\n", sum);
return 0;
}
When I compile this program and run it, I get a completely different number. I don't care right now that I'm not getting the right answer as much as the numbers I am getting are varying by 1,000,000 at times.
The only 2 things I can think of is that running linux in a vm is making it crazy or somehow gcc is messing up.
Is g++ euler2.c -o euler2
correct for compiling c? Yes euler2.c is the name of my file.
SOLVED: Thanks for the replies. Definitely a lot of useful, and extremely quick information. And yes I should have added the possibility that "I might have messed up" =)
Upvotes: 1
Views: 201
Reputation: 63
Only global variables are 0 by default, everything in a function will be assigned anything if you don't initialize it.
Upvotes: 0
Reputation:
int sum = 0;
If it is not initialized (in c
) it contains random-garbage value. hence the random output
and
gcc -o euler2 euler2.c
g++ is for c++, but this does not have anything to do with your problem.
You might find this interesting : http://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html
Upvotes: 4
Reputation: 385385
Your variable sum
is uninitialised, so not only is it starting off with an arbitrary value, but "using" that value is actually Undefined Behaviour, at which point anything can happen.
Write int sum = 0;
(and get used to doing this!)
Also, g++
is the C++ compiler wrapper; you want gcc
.
Finally, you're making assumptions about the range of the data type int
. It's platform dependent as to what the range will be for you; it could be as small as [-32768, +32767] or, as found on the majority of modern 32-bit systems, it could be [-2147483648, +2147483647].
You can mitigate this slightly by specifying that you want an unsigned int
which usually doubles the maximum value (by disallowing negative values), but you perhaps ought to look into the fixed-width types available in stdint.h, if you need a specific range.
Upvotes: 3
Reputation: 5540
Because sum
is not initialized. The compiler will not initialize variables on the stack to be zero, as one might expect. Instead, memory is allocated for the variable, but the value of the variable takes on whatever contents occupy the allocated memory (which is effectively random).
Initialize sum
as you did for the other variables on the stack.
Upvotes: 4
Reputation: 137432
sum is not initialized, so its value is not 0, but some garbage. add sum = 0 at initialization.
Upvotes: 1
Reputation: 8287
You do not initialize your sum variable, I suspect it thus contains an arbitrary value.
Upvotes: 0