如何将用户输入的整数存储在数组中

How to store user input of round numbers in an Array

我有一个问题要解决。我必须制作一个程序,它将从数字序列中取出 2 个数字并比较它们是否为“<”“>”或“=”并且数字列表需要以数字 0 结尾。所以基本上我有一个序列数字 {5, 7, 8, 4, 3, 3, 0} 并且程序必须检查 5,7 对(它是 5 < 7)然后它会转到 8, 4(它是 8 > 4)然后3, 3 所以是3 = 3。而0基本上就是出口。

到目前为止,我写下了数字的比较,但现在我只有一个程序,它从用户那里获取 2 个输入并进行比较。但是我有点需要为用户指定让我们说输入 11 个以 0 结尾的数字(因为 0 不会被计入比较)并将这些数字存储在一个数组中然后让程序在每个之后比较 2 个数字其他(在一个序列中)带有 <, > 或 =.

在此先感谢大家。我对 C 有点陌生,这些数组,特别是 malloc、calloc、realloc 对我来说真的很复杂。

到目前为止,我的代码如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define post 10
int main(){

    int a, b;


    printf("Enter two numbers: ");
    scanf("%d%d", &a, &b);

    if (a > b)
    {
        printf("%d > %d\n", a, b);
    }
    else if(a < b)
    {
        printf("%d < %d\n", a, b);
    }
    else
    {
        printf("%d = %d\n", a, b);
    }


    system("pause");
    return 0;
}

您可以创建大数组,然后输入要比较的数字的数量。然后你可以使用 for 遍历数组中的数字并进行比较。

例子如下:

#include <stdio.h>

#define SIZE 100

int main()
{
    int arr[SIZE] = {0};

    printf("Enter number: ");
    
    int number;
    int counter = 0;   
    
    while (1)
    {
        if (scanf("%d", &number) != 1)
        {
            printf("Invalid number!");
            return 1;
        }
        arr[counter] = number;
        if(number == 0) {break;}
        counter++;
    }

    for (int i = 0; i < counter; i+=2)
    {
        if (arr[i] > arr[i + 1])
        {
            printf("%d > %d\n", arr[i], arr[i + 1]);
        }
        else if(arr[i] < arr[i + 1])
        {
            printf("%d < %d\n", arr[i], arr[i + 1]);
        }
        else
        {
            printf("%d = %d\n", arr[i], arr[i + 1]);
        }      
    }
    
    return 0;
}

输出:

Enter number: 1 2 3 4 5 5 0
1 < 2
3 < 4
5 = 5