用 C 中的数字对填充数组

Fill an array with pairs of numbers in C

我有一个 C 语言的小编程项目。我对这个主题真的很陌生,所以我很感激每一个小小的帮助。对象是:我需要用数字对填充一个数组,直到用户输入 -1。然后用户在控制台中给出一个命令(更大或更小)。如果用户输入较小的数字,则程序必须列出每一对,即第一个数字小于第二个数字。

我可以写到这里:

#include <stdio.h>
#define Max_Number 20

struct numberPairs {
    int firstNum, secondNum;
};


struct numberPairs input(){
    struct numberPairs firstInput;
    printf("Please give me the first number! \n");
    scanf("%d", &firstInput.firstNum);
    printf("Please give me the second number! \n");
    scanf("%d", &firstInput.secondNum);
    return firstInput;
}

struct numberPairs ArrayInput (struct numberPairs x){
    struct numberPairs array[Max_Number], pairs;
    int index=0;
    do{
        pairs=input();
        array[index]=pairs;
        index++;
        if (pairs.firstNum == -1 || pairs.secondNum == -1){
            break;
        }
    }while(index<5  );
}



int main (){
    struct numberPairs t;
    ArrayInput(t);
}

基本上我都不知道怎么办了

首先,使 array[Max_Number] 成为一个全局数组,因为现在它是 ArrayInput 函数的局部数组,并且在函数 returns 时消失了。通过将其设为全局,它将保留下来并可供其他功能使用。该函数现在的类型为 void ArrayInput(void).

在 main 中调用 ArrayInput 后,您现在有了数组。现在询问用户更大或更小,然后遍历数组以列出满足用户要求的元素。您可以将其作为使用全局数组的新函数来执行。

您应该执行以下步骤:

  1. 处理输入直到 -1
  2. 使用fgets处理"smaller"或"Bigger"
  3. 输出

以下 code 可以工作:

#include <stdio.h>
#include <string.h>

#define Max_Number 20

struct numberPairs {
    int firstNum;
    int secondNum;
};

struct numberPairs input() { 
    struct numberPairs firstInput;
    printf("Please give me the first number! \n");
    scanf("%d", &firstInput.firstNum);
    if (firstInput.firstNum == -1)
        return firstInput;
    printf("Please give me the second number! \n");
    scanf("%d", &firstInput.secondNum);
    return firstInput;
}

void ArrayInput() {
    struct numberPairs array[Max_Number];
    int index = 0;
    do {
        array[index] = input();
        if (array[index].firstNum == -1)
            break;
    } while(++index < Max_Number);
    while (getchar() != '\n')
        ;
    printf("Please input Bigger or smaller\n");
    char buf[1024];
    fgets(buf, sizeof buf, stdin);
    if (strcmp(buf, "Bigger\n") == 0) {
        for (int i = 0; i != index; ++i)
            if (array[i].firstNum > array[i].secondNum)
                printf("%d %d\n", array[i].firstNum, array[i].secondNum);
    } else if (strcmp(buf, "smaller\n") == 0) {
        for (int i = 0; i != index; ++i)
            if (array[i].firstNum < array[i].secondNum)
                printf("%d %d\n", array[i].firstNum, array[i].secondNum);       
    } else {
        fputs("Input wrong.", stdout);
    }
}

int main (){
    ArrayInput();
    return 0;
}