0

嗨,我正在尝试用 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;
    }
4

3 回答 3

1

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

case 1:
   read_input_and_function()
   break;

...

void read_input_and_function(void)
{
   printf("Enter your numbers: ");
   /* scanf number1, number2 */
   function(number1, number2);
}
于 2013-03-18T02:58:28.003 回答
1

switch 语句中的函数需要参数,尽管我希望函数询问数字。

如何先询问参数,然后调用函数。这样,两个参数可以声明一次,并在同一个 switch 的其他函数中使用,但根据选择的情况进行定义。

void function1(int, float);

   void printMenu()
   {

     int choice = 0 , num1 = 0;
     float num2 = 0;

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

          switch (choice)
          {
              case 1:
                  printf("\nEnter number 1\n");
                  scanf("%d",&num1);
                  printf("\nEnter number 2\n");
                  scanf("%f",&num2);
                  function1(num1,num2);
                  break;
          }
      } while (choice != 7);
    }
于 2013-03-18T03:59:10.517 回答
-1
#include <stdio.h>
#include <stdlib.h>

#define Pi 3.14159216

/*  
*small program of how to create a menu
*/

main ()
{
float degree,radians;
int input;
/*degrees to radians */
float degreesToRadians (float deg)
{
return ((Pi * deg) / 180.0);
}

/*radians to degrees*/
float radiansToDegrees (float rad)
{
 return rad * (180 / Pi);
}
void menu ()
{
 printf ("\n");
 printf ("1. degrees\n");
 printf ("2. radians\n");
 printf ("3. quit\n");
do
switch (input) {
case 1:
          printf ("\n");
          printf ("\n");

          printf (" Enter value of degrees: ");
          scanf ("%f", &degree);
          printf ("RADIANS = %f \n\n", degreesToRadians (degree));
          menu (); 
          break;

case 2:
          printf ("\n");
          printf ("\n");

          printf (" Enter value of radians: ");
          scanf ("%f", &radians);
          printf ("DEGREES = %f \n\n", radiansToDegrees (radians));
          menu (); 
          break;
case 3:
          printf (" quiting app \n");
          exit (0);
          break;
default:
      printf ("wrong option\n");
      break;
  }
while (input != 3);
    getchar ();   
   }
 }
menu ();
}
于 2015-03-04T06:27:01.320 回答