课程设计:猴子选大王,用C编写的,求每行注释~
#include <stdio.h>#include <stdlib.h>
void ysf(int *pG, int n, int last);
int main(int argc, char *argv)
{
int N = 0;
int nGroup = 0;
int N1 = 0, N2 = 0, N3 = 0;
int *pG1 = 0, *pG2 = 0, *pG3 = 0;
int *pG4 = 0;
int N4 = 0;
int i = 0;
int i4 = 0;
do
{
printf("Input the count of monkey(N >= 9):");
scanf("%d", &N);
} while (N < 9);
srand((unsigned int)time(NULL));
nGroup = rand() % 3 + 1;
N1 = N / nGroup;
if (nGroup > 2) //3
{
N2 = N1;
}
else //2
{
N2 = N - N1;
}
N3 = N - N1 -N2;
printf("Total:%d, devided into %d groups, count: %d / %d / %d \r\n" , N, nGroup, N1, N2, N3);
pG1 = (int *)malloc(sizeof(int) * N1);
if (N2 > 0)
{
pG2 = (int *)malloc(sizeof(int) * N2);
}
if (N3 > 0)
{
pG3 = (int *)malloc(sizeof(int) * N3);
}
for (i = 0; i < N1; i++)
{
pG1[i] = i + 1;
}
for (i = 0; i < N2; i++)
{
pG2[i] = i + 1 + N1;
}
for (i = 0; i < N3; i++)
{
pG3[i] = i + 1 + N1 + N2;
}
ysf(pG1, N1, 3);
if (N2 > 0)
{
ysf(pG2, N2, 3);
}
if (N3 > 0)
{
ysf(pG3, N3, 3);
}
//last turn.
N4 = 3;
if (N2 > 0)
{
N4 += 3;
}
if (N3 > 0)
{
N4 += 3;
}
//printf("N4 is %d\r\n", N4);
pG4 = (int *)malloc(sizeof(int) * N4);
for (i = 0; i < N1; i++)
{
if (pG1[i] > 0)
{
pG4[i4++] = pG1[i];
}
}
for (i = 0; i < N2; i++)
{
if (pG2[i] > 0)
{
pG4[i4++] = pG2[i];
}
}
for (i = 0; i < N3; i++)
{
if (pG3[i] > 0)
{
pG4[i4++] = pG3[i];
}
}
ysf(pG4, N4, 1);
for (i = 0; i < N4; i++)
{
if (pG4[i] > 0)
{
printf("The king is %d\r\n", pG4[i]);
}
}
getchar();
}
void ysf(int *pG, int n, int last)
{
int count = n;
while (count > last)
{
int m=0;
int i = 0;
while (1)
{
if (i == n)
{
i = 0;
}
if (pG[i] > 0)
{
m++;
if (m == n)
{
pG[i] = 0; //out
count--;
//m = 0;
break;
}
}
i++;
}
}
}