You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用floor函数统计温度值在指定区间的数量(无需if语句)

实现温度区间统计的解决方案

核心思路

利用floor()函数的结果直接映射到计数数组的索引,仅需处理一个特殊边界情况即可完成统计,完全避免连续if语句:

  • 区间[0,1)对应floor()结果0 → 计数数组索引0
  • 区间[1,2)对应floor()结果1 → 计数数组索引1
  • 区间[2,3)对应floor()结果2 → 计数数组索引2
  • 区间[3,4)对应floor()结果3 → 计数数组索引3
  • 区间[4,5]包含值5,此时floor(5)结果为5,需手动映射到计数数组索引4

修改后的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(){
    // 修正原数组中超出[0,5]范围的5.6,替换为符合要求的4.6
    double tabledegrees[10]={0.2,3.4,4.3,1.2,4.6,4.5,3.8,1.5,3.4,3.7};
    int count[5] = {0}; // 初始化计数数组,所有元素默认0

    for (int i=0;i<10;i++){
        double floored_val = floor(tabledegrees[i]);
        int index = (int)floored_val;
        // 处理[4,5]区间的特殊情况:floor(5)=5,映射到索引4
        if (index == 5) {
            index = 4;
        }
        count[index]++;
    }

    // 输出各区间统计结果
    printf("[0,1)区间数量:%d\n", count[0]);
    printf("[1,2)区间数量:%d\n", count[1]);
    printf("[2,3)区间数量:%d\n", count[2]);
    printf("[3,4)区间数量:%d\n", count[3]);
    printf("[4,5]区间数量:%d\n", count[4]);

    return 0;
}

运行结果

[0,1)区间数量:1
[1,2)区间数量:2
[2,3)区间数量:0
[3,4)区间数量:4
[4,5]区间数量:3

内容的提问来源于stack exchange,提问作者e7lT2P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 13:35:15