计算C中一个区间中有多少个元素
Counting how many elements are in an interval in C
我得到一个区间 (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 & 只是 return 它。
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
}
我得到一个区间 (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 & 只是 return 它。
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
}