如何为数组元素制作列表?

时间:2017-09-25 17:44:40

标签: c

我需要为数组中的每个新元素创建一个列表。例如,我键入(1,2,3,4,5)然后(6,7,8,9,10)我需要显示(void视图)。我希望你理解

#include <stdio.h>
#define MAX 5
int a[MAX];
int x, s;

void view() {
    for(x = 0; x < MAX; x++) {
        printf("%d. %d" , s, a[x]);
    }
}
int main() {
    int run=1;
    while(run) {
        char choice;
        scanf(" %c", &choice);
        if(choice=='e') {
              for(x=0; x<MAX; x++) {
                  printf("\n");
                  printf("\tEnter value: ");
                  scanf("%d", &a[x]);
              }
        }
        else if(choice=='v') {
            view(); 
         }      
    }
}

3 个答案:

答案 0 :(得分:2)

您需要将之前的输入存储在缓冲区中,比如大小为N * Max的矩阵,其中N是打印输出之前可以采用的最大输入数,Max是每个输入时间的整数数。 / p>

`

#define Max 5  
#define N 10  
int a[N][MAX];  

void view(int counter){
   for(int i=0;i<=counter;i++){
       for(int j=0;j<MAX;j++){
           printf("%d\t",a[i][j]);
           }
        printf("\n");   
        }
    }

void main(){

while(1){
    int counter = 0;
    char choice;
    scanf("%d",&choice);
    if(choice=='e'){
        for(int i=0;i<MAX;i++){
            printf("Enter A no\n");
            scanf("%d",&a[counter][i]);
        }
        counter++;
    }
    else if(choice =='v')
        view(counter);

}
}

`

答案 1 :(得分:0)

你需要制作一个二维数组,包括,比如MAXRUN行和MAX列。您的代码似乎已经为此做好了准备,因为您似乎已经引入了s来计算输入的行数。以下代码应该适合您;希望它有所帮助:

#define MAX 5
#define MAXRUN 5
int a[MAXRUN][MAX];
int x, s;

void view() {
    for (int r = 0; r < s; r++) {
        printf("\n%d. run:", r+1);
        for(x = 0; x < MAX; x++) {
            printf("%d ", a[r][x]);
        }
    }
}

int main() {
    s=0;
    while(s < MAXRUN) {
        char choice;
        printf("\nchoose (e)nter or (v)iew:");
        scanf(" %c", &choice);
        if(choice=='e') {
            for(x=0; x<MAX; x++) {
                printf("Enter value: ");
                scanf("%d", &a[s][x]);
            }
            s++;
        }
        else if(choice=='v') {
            view();
        }
    }
}

答案 2 :(得分:0)

你需要的是一个二维数组。一维看起来像这样:

arr[5]={1,2,3,4,5};

和二维数组看起来像这样:

arr[5][2]={ {1,2,3,4,5}
            {6,7,8,9,10} };

只需使用您的代码:

#include <stdio.h>
#define ROW 5
#define COL 5
int a[ROW][COL];

void view() {
    int i,j;
    for(i = 0; i < ROW; x++) {
        for(j = 0; j < COL; j++) {
            printf("%d" , a[i][j]);
        }
    printf("\n");
    }
}
int main() {
    int run=1,i,j;
    while(run) {
        char choice;
        scanf(" %c", &choice);
        if(choice=='e') {
              for(i=0; i<ROW; i++) {
                  printf("\nList of elements for array %d:",i);
                  for(j=0; j<COL; j++) {
                      printf("\n");
                      printf("\tEnter value: ");
                      scanf("%d", &a[i][j]);
                  }
              }
        }
        else if(choice=='v') {
            view(); 
         }      
    }
}

这将需要最多5个1维数组。如果你需要更多只需增加COL的值