C 将我的数组转换为函数并生成第二个函数来打印它

C 将我的数组转换为函数并生成第二个函数来打印它,c,arrays,function,C,Arrays,Function,我试图创建一个程序,有两个选项,查看和计算。现在,我正在尝试如何将我的数组转换为一个函数,这样我就可以多次进出来存储值。我还希望view成为一个可以多次查看值的函数 我已经设法让计算部分在我的主程序中工作,现在我需要把它变成一个函数。第二,如何创建第二个函数来查看它 我的代码有点乱,请容忍我 #include <stdio.h> #define LENGTH 10 int enterMeasurements(); int main(void) { char input; int

我试图创建一个程序,有两个选项,查看和计算。现在,我正在尝试如何将我的数组转换为一个函数,这样我就可以多次进出来存储值。我还希望view成为一个可以多次查看值的函数

我已经设法让计算部分在我的主程序中工作,现在我需要把它变成一个函数。第二,如何创建第二个函数来查看它

我的代码有点乱,请容忍我

#include <stdio.h>
#define LENGTH 10

int enterMeasurements();

int main(void)
{
char input;
int nrMeasurements=0;
int arrayTable[LENGTH] = {0};
//main menu
do
{
    char input;
    printf("\nMeasurement tool 1.0\n");
    printf("V for (View)\n");
    printf("E for (Enter Values)\n");
    printf("C for (Compute Values)\n");
    printf("R for (Reset Values)\n");
    printf("Q for (Quit)\n");
    printf("\nEnter input: ");
    scanf(" %c", &input);

    if(input == 'v' || input == 'V')
    {
    // function to print array values
    printf("[      ]\n");
    }
    else if(input == 'e' || input == 'E')
    {
    // enter values here
        nrMeasurements = enterMeasurements(arrayTable,nrMeasurements); // my function for entering values
    }
    else if (input == 'c' || input == 'C')
    {
    // enter function to calc min, max and avg and prints it.
    printf("[   min max avg   ]\n");
    }
    else if (input == 'r' || input == 'R')
    {
    // enter function that erase the entire array.
    printf("[   erase array   ]\n");
    }
}
while (input !='q' && input != 'Q');
return 0;
}

int enterMeasurements()
{
int enterMeasurements(int arrayTable[], int nrMeasurements)
{
int i;

for (i = 0; i < LENGTH; i++)
{
    printf("Enter Measurement #%i (or 0): ", i+1);
    scanf("%d", &arrayTable[i]);


    if (arrayTable[i] == 0 )
        break;
}


return i;


}
#包括
#定义长度10
int enterMeasurements();
内部主(空)
{
字符输入;
int nR测量值=0;
int arrayTable[LENGTH]={0};
//主菜单
做
{
字符输入;
printf(“\n测量工具1.0\n”);
printf(“V代表(视图)\n”);
printf(“E代表(输入值)\n”);
printf(“C表示(计算值)\n”);
printf(“R表示(重置值)\n”);
printf(“Q代表(退出)\n”);
printf(“\n输入:”);
scanf(“%c”,&input);
如果(输入='v'| |输入='v')
{
//函数打印数组值
printf(“[]\n”);
}
else if(输入='e'| |输入='e')
{
//在此处输入值
nrMeasurements=enterMeasurements(arrayTable,nrMeasurements);//用于输入值的my函数
}
else if(输入='c'| |输入='c')
{
//输入函数以计算最小值、最大值和平均值,并打印它。
printf(“[min-max avg]\n”);
}
else if(输入='r'| |输入='r')
{
//输入擦除整个阵列的函数。
printf(“[erase array]\n”);
}
}
while(输入!='q'&&input!='q');
返回0;
}
int enterMeasurements()
{
int enterMeasurements(int数组表[],int nrMeasurements)
{
int i;
对于(i=0;i
为了帮助您入门(您真的应该这样做),我将向您展示
printary
功能

首先,
printary
函数需要知道要打印的实际数组。它还需要知道数组中元素的数量。这可以通过两种方式实现:全局变量(没有人真正推荐)或函数参数

您首先需要告诉编译器函数采用参数:

void printArray(int *array, size_t numElements)
上面的一行告诉编译器,
printary
函数有两个参数:一个称为
array
,是指向
int
的指针(数组在传递给函数时“衰减”为指向其第一个元素的指针),另一个参数名为
numElements
,类型为
size\t
(对于元素的大小和数量以及类似的东西来说,这是一个很好的类型)。函数声明为不返回带有
void
关键字的任何内容

声明的参数可以像函数作用域中的任何其他变量一样在函数中使用,并且实际上与函数中定义的任何其他局部变量一样

void printArray(int *array, size_t numElements)
{
    for (size_t i = 0; i < numElements; ++i)
    {
        printf("array[%d] = %d\n", i, array[i]);
    }
}
请注意,该函数不返回任何内容,这意味着您不能在
printf
或任何其他需要值的表达式中使用它


当然,您还应该使前向函数原型声明与实际函数定义相匹配。

Alex,从上一条注释继续,显示一个菜单,允许您向数组中添加值,从数组中删除值,并查看数组(以及值的最大值、最小值和平均值),可以执行与以下类似的操作。注意:命令行不是窗口用户界面,因此您的菜单操作更像是打印的交易凭证。(您可以创建漂亮的文本窗口和固定菜单,但这通常需要一个文本库,例如
ncurses
,这远远超出了您的问题范围

如评论中所述,您的基本方法只是创建一个不断重复的循环。它将显示您的菜单,并允许您从列表中输入选择,例如:

 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: 
在用户输入选择后,为了便于比较,用户的输入将转换为小写。还要注意的是,使用
fgets
(一种面向行的输入函数)将输入读取为字符串,这使得获取用户输入比担心
'\n'
是否保留在输入缓冲区中容易得多(
stdin
)正在等待下一次输入时出现问题。(您可以使用
scanf
函数系列,但您负责计算用户输入的每个字符(并清空输入缓冲区)

使用
fgets
读取输入将读取并包括
'\n'
,因此
'\n'
不可能在
stdin
中未读。
fgets
将读取一个或多个字符串,其中您只对第一个感兴趣。只需参考第一个字符串即可轻松处理缓冲区中的字符。(例如,如果您正在将用户输入读取到名为
buf
的缓冲区中,您可以简单地使用
buf[0]
访问第一个字符,或者简单地使用
*buf

读取用户输入后,第一个字符被传递到
开关
语句,其中语句的每个
大小写
都与第一个字符进行比较。如果字符与大小写匹配,则执行与该大小写相关的操作,以
中断
(如果您自己省略了
中断
,则可以阅读有关直通处理的内容)

如注释中所述,如果您只需要中断一个循环,则只需
break
即可。然而,在这里,您的
switch
语句位于循环内。单个
break
 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: 
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <ctype.h>

enum { MAXN = 64 };  /* constant - max numbers of vals & chars */

void showmenu ();
void prnarray (int *a, int n);
int addvalue (int *a, int n, int newval);
int delvalue (int *a, int n, int index);
int minvalue (int *a, int n);
int maxvalue (int *a, int n);
int sumvalues (int *a, int n);

int main (void) {

    int vals[MAXN] = { 21, 18, 32, 3, 9, 6, 16 }, /* the array */
        n = 7;

    for (;;) {  /* loop until user quits or cancels, e.g. ctrl+d */

        showmenu();                         /* show the menu */

        char buf[MAXN] = "";
        fgets (buf, MAXN, stdin);           /* read user input */
        /* convert to lower-case for comparison of all entries */
        switch (tolower (buf[0])) {         /* 1st char is entry */
            case 'v' :  prnarray(vals, n);
                        break;
            case 'i' :  printf ("\n enter the new value: ");
                        if (fgets (buf, MAXN, stdin) &&
                            isdigit (buf[0])) {
                            n = addvalue (vals, n, atoi (buf));
                        }
                        break;
            case 'd' :  printf ("\n enter the index to delete: ");
                        if (fgets (buf, MAXN, stdin) &&
                            isdigit (buf[0])) {
                            n = delvalue (vals, n, atoi (buf));
                        }
                        break;
            case 'n' :  printf ("\n Mininum of '%d' values is : %d\n",
                                n, minvalue (vals, n));
                        break;
            case 'x' :  printf ("\n Maxinum of '%d' values is : %d\n",
                                n, maxvalue (vals, n));
                        break;
            case 'a' :  printf ("\n Average of '%d' values is : %.2lf\n",
                                n, (double)sumvalues (vals, n)/n);
                        break;
            case 's' :  printf ("\n Sum of '%d' values is : %d\n",
                                n, sumvalues (vals, n));
                        break;
            case 'q' :  printf (" that's all folks...\n");
                        goto done; 
            default  :  if (!buf[0]) {  /* check for manual EOF */
                            putchar ('\n');  /* tidy up */
                            goto done;
                        }
                        fprintf (stderr, "error: invalid selection.\n");
        }
    }
    done:;  /* goto label - breaking 'for' and 'switch' */

    return 0;
}

void showmenu ()
{
    fprintf(stderr, "\n ======== Program Menu =========\n\n"
                    "  V)  View the Array.\n"
                    "  I)  Insert New Value.\n"
                    "  D)  Delete Existing Value.\n"
                    "  N)  Display Minimum Value.\n"
                    "  X)  Display Maximum Value.\n"
                    "  A)  Display Average of Values.\n"
                    "  S)  Display Sum of Values.\n"
                    "\n"
                    "  Q) Quit.\n"
                    "\n"
                    " Selection: ");
}

void prnarray (int *a, int n)
{
    int i;

    printf ("\n there are '%d' values in the array:\n\n", n);

    for (i = 0; i < n; i++)
        printf (" array[%2d] : %d\n", i, a[i]);
}

int addvalue (int *a, int n, int newval)
{
    if (n == MAXN) {
        fprintf (stderr, "error: all '%d' values filled.\n", n);
        return n;
    }
    a[n++] = newval;

    return n;
}

int delvalue (int *a, int n, int index)
{
    if (index < 0 || index > n - 1) {
        fprintf (stderr, "error: index out of range.\n");
        return n;
    }

    int i;

    for (i = index + 1; i < n; i++)
        a[i-1] = a[i];
    a[i] = 0;

    return --n;
}

int minvalue (int *a, int n)
{
    int i, min = INT_MAX;
    for (i = 0; i < n; i++)
        if (a[i] < min)
            min = a[i];

    return min;
}

int maxvalue (int *a, int n)
{
    int i, max = INT_MIN;
    for (i = 0; i < n; i++)
        if (a[i] > max)
            max = a[i];

    return max;
}

int sumvalues (int *a, int n)
{
    int i, sum = 0;
    for (i = 0; i < n; i++)
        sum += a[i];

    return sum;
}
$ ./bin/menusimple

 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: v

 there are '7' values in the array:

 array[ 0] : 21
 array[ 1] : 18
 array[ 2] : 32
 array[ 3] : 3
 array[ 4] : 9
 array[ 5] : 6
 array[ 6] : 16

 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: i

 enter the new value: 77

 ======== Program Menu =========

  V)  View the Array.
  I)  Insert New Value.
  D)  Delete Existing Value.
  N)  Display Minimum Value.
  X)  Display Maximum Value.
  A)  Display Average of Values.
  S)  Display Sum of Values.

  Q)  Quit.

 Selection: v

 there are '8' values in the array:

 array[ 0] : 21
 array[ 1] : 18
 array[ 2] : 32
 array[ 3] : 3
 array[ 4] : 9
 array[ 5] : 6
 array[ 6] : 16
 array[ 7] : 77
gcc -Wall -Wextra -O2 -o simplemenu simplemenu.c
#include <stdio.h>
#include <stdlib.h> /* for atoi */
#include <limits.h> /* for INT_MIN/INT_MAX */

enum { MAXN = 64 };  /* constant - max numbers of vals & chars */

int main (void) {

    int vals[MAXN] = { 21, 18, 32, 3, 9, 6, 16 }, /* the array */
        n = 7;

    for (;;) {

        char c;

        /* show the menu */
        fprintf(stderr, "\n ======== Program Menu =========\n\n"
                        "  V)  View the Array.\n"
                        "  I)  Insert New Value.\n"
                        "  D)  Delete Existing Value.\n"
                        "  N)  Display Minimum Value.\n"
                        "  X)  Display Maximum Value.\n"
                        "  S)  Display Sum of Values.\n"
                        "  A)  Display Average of Values.\n"
                        "\n"
                        "  Q) Quit.\n"
                        "\n"
                        " Selection: ");

        /* read selection (inside of if is OK), check EOF or quit */
        if (scanf (" %c", &c) == EOF || c == 'q' || c == 'Q') {
            printf ("\n that's all folks...\n");
            break;
        }

        if (c == 'v' || c == 'V') {         /* view array code */
            printf ("\n there are '%d' values in the array:\n\n", n);
            int i;
            for (i = 0; i < n; i++)
                printf (" array[%2d] : %d\n", i, vals[i]);
        }
        else if (c == 'i' || c == 'I') {    /* insert value code */
            if (n == MAXN) {
                fprintf (stderr, "error: all '%d' values filled.\n", n);
                continue;
            }
            int newval = 0;
            printf ("\n enter the new value: ");
            if (scanf (" %d", &newval) == 1) {
                vals[n] = newval;
                n++;
            }
            else
                fprintf (stderr, "error: invalid input.\n");
        }
        else if (c == 'd' || c == 'D') {    /* delete value code */
            int i, index = 0;
            printf ("\n enter the index to delete: ");
            if (scanf (" %d", &index) != 1) {
                fprintf (stderr, "error: invalid input.\n");
                continue;
            }
            if (index < 0 || index > n - 1) {
                fprintf (stderr, "error: index out of range.\n");
                continue;
            }
            for (i = index + 1; i < n; i++)
                vals[i-1] = vals[i];
            vals[i] = 0;
            n--;
        }
        else if (c == 'n' || c == 'N') {    /* display minimum code */
            int i, min = INT_MAX;
            for (i = 0; i < n; i++)
                if (vals[i] < min)
                    min = vals[i];
            printf ("\n Mininum of '%d' values is : %d\n",
                    n, min);        
        }
        else if (c == 'x' || c == 'X') {    /* display maximum code */
            int i, max = INT_MIN;
            for (i = 0; i < n; i++)
                if (vals[i] > max)
                    max = vals[i];
            printf ("\n Maxinum of '%d' values is : %d\n",
                    n, max);        
        }
        else if (c == 's' || c == 'S') {    /* compute sum code */
            int i, sum = 0;
            for (i = 0; i < n; i++)
                sum += vals[i];
            printf ("\n Sum of '%d' values is : %d\n",
                                n, sum);
        }
        else if (c == 'a' || c == 'A') {    /* compute avg code */
            int i, sum = 0;
            double avg = 0.0;
            for (i = 0; i < n; i++)
                sum += vals[i];
            avg = (double)sum/n;
            printf ("\n Average of '%d' values is : %.2lf\n",
                    n, avg);
        }
        else    /* if not matched, then invalid selection */
            fprintf (stderr, "error: invalid selection.\n");

    }

    return 0;
}