计算C中一个区间中有多少个元素

标签 c count intervals

我得到一个区间 (a,b),其中 a ≤ x ≤ b。 a = -10 是给定的,b 是由用户输入的。我应该在 C 中编写一个函数 count() 来计算这个区间内有多少个元素 x。

我让这个工作,但我的方法是..粗略的。我基本上是在计算 b - a 来获取元素的数量,并且由于间隔的定义方式,我添加了 1。我想知道的是,是否有更好的方法来做到这一点……真正计算元素的方法。

#include <stdio.h>
#define LIMIT -10

int count(int a, int b);

int main() {
    int x;

    printf("Enter a number:");
    scanf("%d", &x);
    printf("count(%d, %d) = %d", LIMIT, x, count(LIMIT, x));
}

int count(int a, int b) {
    if (b >= a)
        return (b - a) + 1;
    else
        return 0;
}

最佳答案

您可以使用一个初始化为零的计数器变量,并在 for 循环内从 start_limit 递增到 end_limit 并返回它。

function count(int a, int b)     
{
int count=0;                                      //determines how many elements in interval
for(int i=start_limit ; i<=end_limit ;i++)      //here, start_limit=a , end_limit=b
{ 
count++;                                
}
return count;                                   //it returns total no. of elements inside interval
}

关于计算C中一个区间中有多少个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44056334/

相关文章:

JavaScript:clearInterval不会清除间隔

javascript - angularjs 间隔应用 rootscope 中的更改

c++ - 如何从 C stdio.h getline() 中替换/忽略无效的 Unicode/UTF8 字符?

c - C 中的全缓冲​​、行缓冲和无缓冲是什么意思?

sql - Oracle SQl Dev,如何计算两个日期之间的工作日数

mysql - SQL 按计数过滤

c - 对于多维数组,第一列中用户输入的值,第二列中显示正方形

c - 如何使用指针算术循环分配的内存 C

mysql - 基于条件 SELECT 的 COUNT

algorithm - 增广区间树