通过带语句的switch语句传递变量

时间:2015-07-11 03:45:14

标签: c function menu switch-statement

我正在尝试学习如何使用函数在菜单中传递变量。问题是,在任何时候都没有教过如何这样做。你可以想象,我将在第一个菜单函数中输入的任何变量通常用于我的案例/其他功能,如

  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 个答案:

答案 0 :(得分:2)

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

  1. 命名功能 - 应为函数提供清晰的描述性名称,以便不熟悉程序的人能够轻松了解他们的工作。 function1 function2 等名称无法实现此目的。

  2. 使用适当的数据结构 - 听起来您正在尝试跟踪用户输入的所有数字,但您目前还没有任何方法这样做。执行此操作的最佳方法是使用数组,这是一个容纳其他值的容器。为了跟踪到目前为止的数字,让我们创建两个变量 - 一个存储数字的数组,以及跟踪已输入的数字的整数。现在,让我们让用户输入最多100个数字。我们通过在程序顶部编写int arr[100];int numCount = 0;来完成此操作。快速注释 - 这被称为全局变量 - 通常它并不是一个好主意,但我们现在不用担心它。

  3. 将代码分成适当的功能 - 您在function1中做得很好。它很好地执行任务,即从用户那里获取一个数字并将其返回。现在让我们使用这个号码。在case 1之后,让我们写一下

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

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

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

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

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

相关问题