在 C/C++ 中定义数字范围

Define A Range Of Numbers in C/C++

本文关键字:定义 数字 范围 C++      更新时间:2023-10-16

有没有办法将一系列数字划分为某些子范围

即如果我们的范围为 1-10

用户输入 1 3 , 4 7 ,7 10我们将范围 1-3 定义为一个范围的一部分,将范围 4-7 定义为另一个范围,依此类推。例如,如果输入数字 8,我们将输出为范围 3。

正在考虑创建一个数组 int arr[10] 并作为用户输入 1 3 例如,然后是 arr[0]=1 和 arr[2]=1,然后是 4 7 作为 arr[3]=2 和 arr[6]=2 。但这错过了两者之间的数字,如果我们从 0 到 2 和 3 到 6 循环。在数组长度超过 10 的较大规模上,这将效率低下。

有人可以帮助我吗?

定义范围类型:

struct range
{
  int low;
  int high;
}

然后定义一个这样的数组:

struct range ranges[<some size>] = {0};

定义并实现查找最高high和最低最低low值的函数:

int lowest(struct range * ranges, int * plowest);
int highest(struct range * ranges, int * phighest);

输入所有范围并将其存储在 ranges 中。

ranges上拨打highest()lowest(),您有外部间隔:

struct range range_outer = {0};
/* code reading ranges. */
if (0 != lowest(ranges, &range_outer.lowest))
  fprintf(stderr, "lowest() failedn");
if (0 != highest(ranges, &range_outer.highest))
  fprintf(stderr, "highest() failedn");

为了帮助lowest()highest(),对ranges进行排序可能是有意义的,前者按成员low按成员high后者排序。

int sort_by_low(struct ranges * ranges); 
int sort_by_high(struct ranges * ranges); 

使用 qsort() 函数可以轻松完成对数组进行排序。

一个完整的工作实现:

#include <iostream>
#include <vector>
using namespace std;
typedef struct
{
    int min; int max; int range;
} RANGE;
int InRange(int num, RANGE range)
{
    if (num >= range.min && num <= range.max)
        return 1;
    return 0;
}
int main()
{
    vector<RANGE> list; int count = 0, rangesCount = 0;
    puts("How many ranges?");
    cin >> rangesCount;
    puts("Input the range defenitions as a min-max-range pairs(Enter min, then enter      max, then enter the output range):");
for (int i = 0; i < rangesCount; i++)
{
    RANGE range;
    cin >> range.min;
    cin >> range.max;
    cin >> range.range;
    list.push_back(range);
}
while (1)
{
    puts("Now, enter a value, to know in what range it exist:");
    int num;
    cin >> num;
    for (int i = 0; i < rangesCount; i++)
    {
        RANGE r = list.at(i);
        int included = InRange(num, r);
        if (included)
        {
            cout << "The output range is " << r.range << "nn";
        }
    }
}
}

许多事情都可以改进,您可以根据需要进行定制。