Sunday, July 12, 2009

C Programming?

I try to generate non reoccuring number and it wont work





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;





int gen( int letter )


{


int x = rand()% 14 + 1 + 15* letter;


return x;


}


int main()


{


int i;


int j;


int A[5][5];


int letter;


int unique;


int cur;


int num;


FILE *card;


srand(time(0));


card = fopen("card", "w");


for (i = 0; i %26lt; 5; ++i)


{


for(j = 0; j %26lt; 5; ++j)


{


A[i][j] = gen(i);


}


}





A[2][2] = 0;





printf("B\tI\tN\tG\tO\t\n");





fprintf(card,"B\tI\tN\tG\tO\t\n");





for (i = 0; i %26lt; 5; ++i)


{ printf("%d\t%d\t%d\t%d\t%d\n", A[0][i], A[1][i], A[2][i], A[3][i], A[4][i]);


fprintf(card, "%d\t%d\t%d\t%d\t%d\n", A[0][i], A[1][i], A[2][i], A[3][i], A[4][i]);


}





cur = 0;


while ( cur %26lt; 5)


{


unique = 1;


for ( i = 0; i %26lt; cur; ++i)


{


if (A[i][j] == num )


unique = 0;


}


if (unique == 1)


{


A[i][j] = num;


cur++;


}


else


num = rand()%5+1;


}


for ( i=0; i %26lt; 5; ++i)


printf("%d: %d\n", i, j, A[i][j]);





fclose(card);


return 0;

C Programming?
Halfway down, you have the statement set





for ( i = 0; i %26lt; cur; ++i)


{


if (A[i][j] == num )


unique = 0;


}


if (unique == 1)


{


A[i][j] = num;


cur++;


}





What's j at this point?





Also, a point of style that could prevent strange bugs: If you're using i for the first subscript and j for the second, NEVER use i for the second, even if the first is a constant (as in the print loop). It's confusing, and the computer couldn't care less if you're using j without using i.





Hope that helps.


No comments:

Post a Comment