gpt4 book ai didi

c - 带有 switch 语句的交互式菜单

转载 作者:行者123 更新时间:2023-11-30 15:50:57 25 4
gpt4 key购买 nike

嗨,我正在尝试用 C 语言制作一个带有 switch 语句的交互式菜单。尽管我不确定如何触发具有某些参数的函数。我是一个完全的初学者,我很困惑如何做到这一点。switch 语句中的函数需要参数,尽管我希望函数询问数字。我这样做是作为一项作业,无法提供实际的代码,所以我做了这个模型。感谢您的帮助。

这是我可能使用的代码示例。

#include <stdio.h>

void printMenu()
{
int choice;

do
{
printf("Main Menu:\n");
printf("1) do this\n");
scanf("%d", &choice);

switch (choice)
{
case 1:
function(); /* though this needs the arguments */
break;
}
} while (choice != 7);

int main(void)
{
printMenu();
return 0;
}

void function(int number1, float number2)
{
/*calculation*/
printf("enter your numbers");
/* Not sure how to read the numbers in here */
printf("%d + %d = %d", number1, number2, number1 + number2);
return;
}

最佳答案

如果您希望 switch 尽可能小,那么只需调用另一个接受输入的函数,然后调用该函数...

case 1:
read_input_and_function()
break;

...

void read_input_and_function(void)
{
printf("Enter your numbers: ");
/* scanf number1, number2 */
function(number1, number2);
}

关于c - 带有 switch 语句的交互式菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15469064/

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