I have a code that generates 40 random numbers from 50~100 and put them in array and then sort it from smallest to largest. also print out 5 smallest at the end
I really don't know why but first number in my array is always 40.
everything else looks fine.
When I try to compile this, I get an error at line 7:
/.../Test/main.cpp||In function ‘int random()’:|
/.../Test/main.cpp|26|error: new declaration ‘int random()’|
/usr/include/stdlib.h|327|error: ambiguates old declaration ‘long int random()’|
||=== Build finished: 2 errors, 0 warnings ===|
There is already a longint random(); function in some versions of cstdlib. I changed all references from random() to random50() and now it at least compiles for me, however instead of 40 for my first number, I get 0. I'll keep looking.
Replace line 37: for (int i = 0; i < n; i++)
with: for (int i = 0; i+1 < n; i++)
On your last iteration, of this loop i is 39. Then you perform operations on a[i+1] which is a which is not part of the array. This is a value which shouldn't be accessed. It could cause a seg fault. In my compiler it happened to be 0, in your compiler it happened to be 40. Tomorrow when you boot up, you may find that it is something else.