C语言 布尔值不会在主函数中改变,即使我在另一个函数中改变它



我正在制作一个锦标赛,我使用布尔值来说明一个团队是否在。如果一支球队输了,那么我希望这个值为假,因为他们不再参加比赛了。这就是问题出现的地方,当我改变if语句中的值并返回该值时,即使我告诉它为假,它仍然保持为真。我使用printf语句来检查值,它们都是1,我希望其中一个是0,因为这意味着布尔值被改变了,这就是我想要的。

我尝试使用指针,但没有工作。老实说,在那之后我就被困住了,最终它把我带到了这里。

#include<stdio.h>
#include<stdbool.h>
#include<time.h>
#include<stdlib.h>
bool generatescore(bool team1, bool team2, char team1name[], char team2name[]) {
int rand_num1;
int rand_num2;
int lower = 25;
int upper = 100;
srand(time(NULL));
rand_num1 = (rand() % (upper - lower+1)) + lower;
rand_num2 = (rand() % (upper - lower+1)) + lower;
int team1_score = rand_num1;
int team2_score = rand_num2;

printf("%s score: %dn", team1name, team1_score);
printf("%s score: %dn", team2name, team2_score);
if(team1_score > team2_score) {
printf("%s made it to the next roundn", team1name);
team2 = false;
return team2;
} else if(team2_score > team1_score) {
printf("%s made it to the next roundn", team2name);
team1 = false;
return team1;
}

}



int main() {
bool racoons_status = true;
bool bulls_status = true;
bool gators_status = true;
bool crabs_status =true;
bool horses_status = true;
bool worms_status = true;
bool rats_status = true;
bool bucks_status = true;
char racoons[] = "racoons";
char bulls[] = "bulls";
char gators[] = "gators";
char crabs[] = "crabs";
char horses[] = "horses";
char worms[] = "worms";
char rats[] = "rats";
char bucks[] = "bucks";

generatescore(racoons_status, bulls_status, racoons, bulls);
printf("%d", racoons_status);
printf("%d", bulls_status);
return 0;
}

c按值传递,您在generatescore中获得的bool值是main中的bool值的副本,您必须使用'c样式按引用传递'。这样的

void myFunc(bool *b){
*b = false;
}
int main(){
bool b = true;
myFunc(&b);
}

传递一个指向main

bool对象的指针

最新更新