统计区间元素的个数 关于#c语言#的问题,请各位专家解答!

img


#include <stdio.h>

int main()
{
    int a =0,b=0,c=0,d=0,e=0;
    int n,i;
    int tmp;
    scanf("%d",&n);
    for (i=0;i<n;i++)
    {
        scanf("%d",&tmp);
        if(tmp >=0 && tmp <20)
            a++;
        else if(tmp >=20 && tmp <50)
            b++;
        else if(tmp >=50 && tmp <80)
            c++;
        else if(tmp >=80 && tmp <130)
            d++;
        else if(tmp >=130 && tmp <=200)
            e++;
    }
    printf("%d %d %d %d %d\n",a,b,c,d,e); //只输出5个整数
    /*下面是详细的输出
    printf("[0-20):%d\n",a);
    printf("[20-50):%d\n",b);
    printf("[50-80):%d\n",c);
    printf("[80-130):%d\n",d);
    printf("[130-200]:%d\n",e);*/
    return 0;
}

供参考:

#include<stdio.h>
int main()
{
    int a[1024], b[5] = { 0 }, i, n;
    scanf("%d", &n);
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
           if (a[i] >= 0   && a[i] < 20)  b[0]++;
      else if (a[i] >= 20  && a[i] < 50)  b[1]++;
      else if (a[i] >= 50  && a[i] < 80)  b[2]++;
      else if (a[i] >= 80  && a[i] < 130) b[3]++;
      else if (a[i] >= 130 && a[i] <=200) b[4]++;
    }
    printf("[0,20):%d\n[20,50):%d\n[50,80):%d\n[80,130):%d\n[130,200]:%d\n", b[0], b[1], b[2], b[3], b[4]);
    return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

struct Count
{
    int a = 0; // 0 - 19
    int b = 0; // 20 - 49
    int c = 0; // 50 - 79
    int d = 0; // 80 - 129
    int e = 0; // 130 -200
};

int main()
{
    struct Count count;
    printf("输入元素个数:");
    int num;
    scanf("%d", &num);
    printf("\n输入元素:");
    const int nums = 1024;
    int element[nums] = { 0 };
    for (int i = 0; i < num; i++)
    {
        scanf("%d", &element[i]);
        if (element[i] >= 0 && element[i] < 20)
        {
            count.a = count.a + 1;
        }
        else if (element[i] >= 20 && element[i] < 50)
        {
            count.b = count.b + 1;
        }
        else if (element[i] >= 50 && element[i] < 80)
        {
            count.c = count.c + 1;
        }
        else if (element[i] >= 80 && element[i] < 130)
        {
            count.d = count.d + 1;
        }
        else if (element[i] >= 130 && element[i] < 200)
        {
            count.e = count.e + 1;
        }
    }
    printf("\n[0-20):%d,[20,50):%d,[50,80):%d,[80,130):%d,[130,200):%d\n", count.a, count.b, count.c, count.d, count.e);
    

    system("pause");
    return 0;
}