我希望这个程序跟踪用户输入值的周期数,程序运行良好,但函数 cycler()
没有返回适当的值。我将非常感谢任何能在这里帮助我的人。
#include <stdio.h>
#include <stdlib.h>
int cycle=0;
int main()
{
startProgram(0);//If status is 1, the program will exit
return 0;
}
void startProgram(int status) {
if (status == 0) {
printf("Enter a value\n");
int input;
scanf("%d",&input);
printf("input is: %d\n",input);
/*
Here is where i need help!!!!!!!!!!
When the cycler() is called, i want it to pass in the value of current cycle,
The value of cycle has first been initialized to 0
*/
int cycle = cycler(cycle);
printf("Cycle Number : %d\n",cycle);
resetProgram(input);
} else {
printf("Exiting");
}
}
int cycler(int x){
int ret = x++;
return ret;
}
void resetProgram(int status){
if ((status > 0) && (status < 12)) {
startProgram(0);
} else {
printf("\nExit\n");
}
}
最佳答案
在不确切知道您期望的输出的情况下很难回答您的问题,但我认为您希望每次调用时“周期数”都会增加。如果是这种情况,那么您需要某种方法来跟踪变量的先前值。有几种方法可以做到这一点,但是当代码本身的结构存在一些明显的错误时,很难规定“正确”的方法。
这里最大的错误是评论之一中提到的“相互递归”。想象一下你有两个函数,就像这样
void a()
{
// do something
b();
}
void b()
{
// do something
a();
}
您可以在此处看到 a
调用 b
,而 b
调用 a
。这个程序将永远重复。问题是,每次在 C 中调用函数时,都会在 ram 中分配一点内存,以跟踪您所在的函数。因为 a
或 b
允许结束,或者更正式地说,“返回
”,该内存永远不会被释放。该程序最终会耗尽内存并崩溃。 (实际上可能不是,因为称为“内联”的东西,但这只是因为这是一个人为的示例。)
在 C 语言中执行此操作的更好方法是使用 while
或 for
循环。
void a()
{
// do something
}
void b()
{
// do something
}
int main()
{
while(1)
{
a()
b()
}
}
只要括号内的值不是 0
,while
循环就会继续重复。由于值(1
)永远不会是0
,因此该结构将永远循环,并且不存在与a
相同的相互递归问题> 和 b
都允许结束,因此它们的内存将在每次调用后被释放。
因此,为了解决您实际询问的问题,可以引入static
变量,正如另一个答案中所建议的(正确的),或者可以重组他们的代码以不需要它们。我更喜欢以下方法,其中 startProgram()
仅调用一次,因此 cycle
不需要是静态的。
void startProgram()
{
int statusIsGood = 1;
int cycle = 1;
while(statusIsGood)
{
int input;
scanf("%d", &input);
statusIsGood = getStatus(input);
printf("Cycle count: %d", cycle);
// In practice, it makes more sense to simply do
// cycle++; and get rid of `nextCycle()` all together
cycle = nextCycle();
}
}
int nextCycle(int cycle)
{
return cycle + 1;
}
int getStatus(int input)
{
if (input <= 0 || input >= 12)
return 1;
else
return 0;
}
关于c - 无法在 c 函数中返回正确的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54823091/