我有以下用 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);
我是一名优秀的程序员,十分优秀!