使用函数通过 switch 语句传递变量

Passing variable through switch statement with functions

我正在尝试学习如何使用函数通过菜单传递变量。问题是,从来没有人教过如何这样做。你可以想象,我在第一个菜单功能中输入的任何变量通常在我的 cases/other 功能中使用,例如

  if (count==0)
  {
    low = number;

    high = number;

    count++;

    sum = number;
  }
  else
  {
    if (number < low)
      number = low;

    if (number > high)
      high = number;

    count ++;

    sum += number;
  }

不会通过函数 2,任何对 C 更了解的人都会意识到这一点。它也不会在 int main 中工作。如何定义用户输入的数字、最高、最低等。到其他功能?这是我目前所拥有的,循环和菜单工作正常。

#include<stdlib.h>
#include<stdio.h>

int menuChoice()
{
  int choice;

  printf("1.Enter a number\n");
  printf("2.Display Highest Number Entered\n");
  printf("3.Display Lowest Number entered\n");
  printf("4.Display Average of Numbers Entered\n");
  printf("5.Quit\n");

  printf("Enter your choice:   ");
  scanf("%i", &choice);

  return choice;
}

int function1()
{
  int number;

  printf("Enter a number:\n");
  scanf("%i", &number);

  return number;
}

int function2()
{

}

int function3()
{

}

int function4()
{

}

int main()
{
  int quit = 0;
  while (quit != 1)
  {
    int menu;

    menu = menuChoice();
    switch (menu)
    {
    case 1:
      function1();
      break;
    case 2:
      function2();
      break;
    case 3:
      function3();
      break;
    case 4:
      function4();
      break;
    case 5:
      quit = 1;
      break;
    default:
      printf("Please enter 1 through 5\n");

    }
  }
  return 0;
}

让我们看看可以改进此代码的一些方法。

  1. 命名函数 - 函数应该被赋予清晰、描述性的名称,让不熟悉该程序的人可以轻松理解它们的作用。 function1function2 等名称无法实现此目的。

  2. 使用适当的数据结构 - 听起来您正在尝试跟踪用户输入的所有数字,但您目前没有有办法做到这一点。最好的方法是使用一个数组,它是一个容器,其中包含其他 values.To 跟踪您目前拥有的数字,让我们创建两个变量 - 一个存储数字的数组和一个整数跟踪输入了多少个数字。现在,让我们让用户输入最多 100 个数字。我们通过在程序顶部写入 [​​=10=] 和 int numCount = 0; 来实现。快速旁注 - 这称为 全局变量 - 通常这不是一个好主意,但我们暂时不用担心。

  3. 将代码分成适当的函数 - 你在 function1 中做得很好。它很好地执行了它的任务,即从用户那里获取一个数字并 return 它。现在让我们使用那个数字。在 case 1 之后,让我们写

    arr[numCount] = function1(); numCount += 1;

    这会将数组中第一个未使用的条目设置为输入的数字,然后增加我们拥有的元素数量的计数器。

  4. 不要进行不必要的计算 - 让我们想想如何实现我们的最高和最低功能。一种方法是每次调用函数时遍历整个数组并跟踪我们看到的最大数字。这会奏效,但我们最终会重复很多工作。如果每次我们得到一个新数字,我们更新我们看到的当前最高和最低数字怎么办?

  5. 使用循环扫描数组 - 为了计算平均值,我们将使用 for 循环。如果您不理解,请查找相关文档。

我想你可以看到如何将这种思维扩展到计算输入值的平均值。这是我修改后的内容 - http://pastie.org/10285795.