gpt4 book ai didi

c++ - 函数 A 调用函数 B,函数 B 调用函数 A,你怎么调用它?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:51:20 26 4
gpt4 key购买 nike

我知道当函数调用自己时,它被称为递归。但是当函数 A 调用函数 B 调用 A 直到有一个 IF 语句停止整个过程时,你如何调用。从一本 C 书中看这个练习(顺便问一下,我能更好地解决这个问题吗?)

Write a function that displays a menu of four numbered choices and asks you to choose one. (The output should look like the preceding.)

Write a function that has two int arguments: a lower limit and an upper limit. The function should read an integer from input. If the integer is outside the limits, the function should print a menu again (using the function from part "a" of this question) to reprompt the user and then get a new value. When an integer in the proper limits is entered, the function should return that value to the calling function.

Write a minimal program using the functions from parts "a" and "b" of this question. By minimal, we mean it need not actually perform the actions promised by the menu; it should just show the choices and get a valid response.

#include <stdio.h>

void Display(void);
int Limits(int a, int b);

int main(void)
{
Display();
return 0;
}
void Display()
{
int y = 0;
printf("1 - 2 - 3 - 4\n");
y = Limits(0, 100);
if(y < 100 && y > 0)
printf("%d\n", y);
}
int Limits(int a, int b)
{
int x;
scanf("%d", &x);
if(x < a || x > b)
Display();
return x;
}

输出:

1 - 2 - 3 - 4
1234
1 - 2 - 3 - 4
34456
1 - 2 - 3 - 4
123
1 - 2 - 3 - 4
-34
1 - 2 - 3 - 4
-23
1 - 2 - 3 - 4
88
88
Press [Enter] to close the terminal ...

最佳答案

这称为相互递归或(较少见)交叉递归。

至于如何彻底解决它,在我看来它大致符合以下模式:

namespace {
int show_menu() {
printf("1 - 2 - 3 - 4");
int n;
std::cin >> n;
return n;
}
}

int menu() {
int value;
do {
value = show_menu();
} while (value <1 || value > 4);
return value;
}

关于c++ - 函数 A 调用函数 B,函数 B 调用函数 A,你怎么调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15589640/

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