【问题标题】:Fill an array with pairs of numbers in C [closed]用C中的数字对填充数组[关闭]
【发布时间】:2023-03-24 04:35:01
【问题描述】:

我有一个小的 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);
}

基本上我不知道该怎么做。

【问题讨论】:

标签: c arrays numbers project


【解决方案1】:

首先,将array[Max_Number] 设为全局数组,因为它现在是ArrayInput 函数的本地数组,并且在函数返回时消失了。通过使其全局化,它将保留并可供其他功能使用。现在函数的类型是void ArrayInput(void)

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

【讨论】:

  • 别忘了这两个值可以相等
  • 感谢您的回答,这真的帮助了我:)
【解决方案2】:

您应该执行以下步骤:

  1. 处理输入直到-1
  2. 使用fgets处理“更小”或“更大”
  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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2020-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多