gpt4 book ai didi

c - 如何避免在每次调用函数后将变量重新初始化为 0?

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:56 26 4
gpt4 key购买 nike

我有以下用 C 语言编写的程序。为简单起见,下面显示的代码片段中省略了预处理器指令。

int entry(int people){    //function to add people to the event
int entered;
printf("Please enter the number of people you wish to add to the list.");
scanf("%d", &entered);
int newpeople = people + entered;
return newpeople;
}

int left(int people){
printf("How many people have left?");
int left;
scanf("%d", &left);
int newpeople = people - left;
return newpeople;
}

int main(void){
int people = 0; //to initialise the people variable
while (1){
int choice;
printf("Choose between 1. New people enter or 2. People exit");
scanf("%d", &choice);
if (choice == 1){
printf("You chose to add people.");
printf("The new amount of people is: %d", entry(people));
}
else if (choice == 2){
printf("You chose to remove people.");
printf("The new amount of people is: %d", left(people));
}
}
return 0;
}

我对这个程序的问题是,每当 while(1){} 循环初始化时,它都会删除先前由被调用函数返回的值。我希望它继续运行(即向我显示菜单),直到我选择手动终止它。理想情况下,它应该将变量“int people”的值从循环的一个实例传递到下一个实例。

我发现 people 的值必须在 main 的某个地方初始化(否则其中会出现垃圾值),但我在整个代码的多个地方尝试过这个,但没有成功。它只是每次都重新初始化为值 0。

任何帮助将不胜感激,即使它是正确方向的提示。

最佳答案

您应该重新分配人员,而不是在打印值时调用函数。

改变这个:

printf("The new amount of people is: %d\n", entry(people));

为此:

people = entry(people);
printf("The new amount of people is: %d\n", people);

关于c - 如何避免在每次调用函数后将变量重新初始化为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43441137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com