我正在尝试比较3个随机数,但我得到的是第一个数字总是较低,并得到真正较低数字的英勇,我不知道我在哪里失败,这里是代码
void winner(int team1, int team2, int team3){
if (team1 < team2 && team1 < team3){
printf("Team 1 winner %d seconds\n", team1);
}
if (team2 < team1 && team2 < team3){
printf("Team 2 winner %d seconds\n", team2);
}
if (team3 < team1 && team3 < team2){
printf("Team 3 winner %d seconds\n", team3);
}
if (team1 == team2 && team1 < team3){
printf("Draw Team 1 and Team 2, %d seconds\n", team1);
}
if (team1 == team3 && team1 < team2){
printf("Draw Team 1 and Team 3, %d seconds\n", team1);
}
if (team2 == team3 && team2 < team1){
printf("Draw Team 2 and Team 3, %d seconds\n", team2);
}
if (team1 == team2 && team2 == team3){ //Fixed this compare, tanks Guilles
printf("Draw Team 1, Team 2 and Team 3, %d seconds\n", team1);
}
}
我总是得到第一个“if”结果,或者如果2个数字等于,我得到第4个“if”
我正在调用函数whit
winner(WEXITSTATUS(team1), WEXITSTATUS(team2), WEXITSTATUS(team3));
我正在添加我得到的部分,team1,team2和team3
int corredores(int equipo){
struct timespec tw = { .tv_sec = 0, .tv_nsec = 10000000 };
pid_t Cp, Rn1, Rn2;
int min = 2, max = 6;
int T1, T2, TC;
Cp = fork(); //Creacion del capitan
if (Cp == -1){
printf("Un Capitan no esta listo, no habra carrera\n");
exit(-1);
}
else if (Cp == 0){ //Codigo del Capitan
nanosleep(&tw, 0);
Rn2 = fork(); //Creacion del Segundo Corredor
if (Rn2 == -1){
printf("El Segundo Corredor de un Equipo no esta listo, no habra carrera\n");
exit(-1);
}
else if (Rn2 == 0){ //Codigo del Segundo corredor
nanosleep(&tw, 0);
Rn1 = fork(); //Creacion del Primer corredor
if (Rn1== -1){
printf("El Primer Corredor de un Equipo no esta listo, no habra carrera\n");
exit(-1);
}
else if (Rn1 == 0){ //Codigo del Primer corredor
srand(getpid());
nanosleep(&tw, 0);
T1 = aleatorio(min, max);
printf("El tiempo del Primer Corredor del Equipo %d es de %d segundos\n",equipo, T1);
sleep(T1);
exit(T1);
}
wait(&T1);
srand(getpid());
T2 = aleatorio(min, max);
printf("El tiempo del Segundo Corredor del Equipo %d es de %d segundos\n",equipo, T2);
nanosleep(&tw, 0);
sleep(T2);
T2 = T2 + WEXITSTATUS(T1);
exit(T2);
}
wait(&T2);
srand(getpid());
TC = aleatorio(min, max);
printf("El tiempo Capitan del Equipo %d es de %d segundos\n",equipo, TC);
nanosleep(&tw, 0);
sleep(TC);
TC = TC + WEXITSTATUS(T2);
exit(TC);
}
return WEXITSTATUS(TC);
}
并通过
调用team1 = corredores(equipo);
补充说,“aleatorio”功能,我觉得它运作正常
int aleatorio(int min, int max){
return rand() % (max-min+1) + min;
}
我认为问题出在这里
wait(&team1);
wait(&team2);
wait(&team3);
printf("======================================\n");
ganador(WEXITSTATUS(team1), WEXITSTATUS(team2), WEXITSTATUS(team3));
第一个功能结束得到team1,第二个,team2和第三个team3 例如,team1 = 14 s,team2 = 9 s,team 3 = 11 s
之后我得到,team1 = 9秒,team2 = 11s,team3 = 14s
答案 0 :(得分:1)
你对帖子的最后一次补充使它更加清晰。 你等待3个这样的子进程:
wait(&team1);
wait(&team2);
wait(&team3);
所以team1..team3将拥有这些进程的退出代码。但函数wait
不等待任何特定进程,第一个等待将返回退出的第一个子进程的退出代码。所以你永远不会知道team1是team1还是team2或team3的得分!
因为孩子根据分数处理睡眠,所以停止的第一个过程将得分最低,因为分数较高的过程会睡得更久。所以在你的情况下,team1将始终是得分最低的团队。