在 C/C++ 中定义数字范围
Define A Range Of Numbers in C/C++
有没有办法将一系列数字划分为某些子范围
即如果我们的范围为 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";
}
}
}
}
许多事情都可以改进,您可以根据需要进行定制。
相关文章:
- 使用用户定义的函数查找数字的幂时出现问题
- Spirit X3:自定义数字解析器在结果中产生意外的前导零
- 为什么 rand() 给我的数字超出了我定义的间隔?(昨天工作正常)
- 用户定义的数字文字可以立即加上点
- 带有自定义数字的阶乘函数不起作用
- 如何将一个或多个(未定义的数字)参数传递给函数
- 在Windows 10中,将Clocks_per_sec重新定义为更高的数字
- 在不重新编译源代码的情况下更改C++(C)程序中定义的数字
- 是否可以从定义的数字集中选择随机数
- C 使用功能定义中的if/其他语句以返回最小的数字
- 如何定义和使用小于2E-308的数字
- 打印由用户定义的数组,第一个数字确定单词的大小,第二个数字确定行的大小
- 如何使用大值表示C++中未定义的数字
- 使用自定义数字将字符串转换为双精度无法按预期工作
- 为具有一个数字数据成员的类定义所有比较运算符的方便方法
- 如何用3个用户定义的函数计算一个数字的真平方根
- 根据#定义的数字定义不同长度的枚举
- 从浮点转换为自定义数字类型
- 如何为我的插件实现自定义数字签名
- 在 C/C++ 中定义数字范围