Reputation: 15
I used CodeBlocks to code this program:
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream is;
is.open("game.inp");
int n,a[100];
is>>n;
for (int i=0; i<n; i++)
is>>a[i];
is.close();
int game[100];
int kt=0;
for (int i=0; i<n; i++)
{
for (int j=3; j<a[i]+1; j++)
{
if ((a[i]%j)==0)
{
int *x = find(begin(game),end(game),j); //ktra uoc hien tai da co trong mang hay chua, k co thi ms them
if (x==end(game))
{
game[kt]=j;
kt++;
}
}
}
}
int kq=0;
for (int i=0; i<kt; i++)
{
int d=0;
for (int j=0; j<n; j++)
{
if ((a[j]%game[i])==0)
d++;
}
if (d>kq)
kq=d;
}
ofstream o;
o.open("game.out");
o<<kq;
o.close();
return 0;
}
and the result was not correct. Then I decided to copy these codes to Visual Studio 2019 and it gave me the correct result. I don't know what happened. I copied the same codes from CodeBlocks to VS and the results were completely different.
Upvotes: 1
Views: 145
Reputation: 409136
Welcome to the wonderful world of undefined behavior.
You use the contents of the array game
before it's initialized. Local variables are not initialized, their contents is indeterminate and using indeterminate values lead to undefined behavior.
If you want the array to be initialized to all zeroes you need to do it explicitly:
int game[100] = { 0 };
Upvotes: 2