【问题标题】:Fill table with values in ranges from another table用另一个表中范围内的值填充表
【发布时间】:2022-11-23 17:33:33
【问题描述】:

我有一个带度数的一维表:

双表度数[10]={0.2,3.4,4.3,1.2,4.6,4.5,3.8,1.5,3.4,3.7};

度数始终在 [0,5] 区间内。

我想计算每个区间 [0,1]、[1,2)、[2,3]、[3,4]、[4,5] 的温度计数量,并将这些值存储在大小为 5 的整数数组,其中单元格 0 属于区间 [0,1] 的度数,单元格 1 属于区间 [1,2) 的度数,依此类推。

我想使用 floor 函数而不是一系列 if 命令。

以下程序:

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

int main(){

  
double tabledegrees[10]={0.2,3.4,4.3,1.2,5.6,4.5,3.8,1.5,3.4,3.7};
double tabledegreesfloored[10];

for (int i=0;i<10;i++){
    tabledegreesfloored[i] = floor(tabledegrees[i]);
   }


for (int j=0;j<10;j++){
    printf("%.f \n", tabledegreesfloored[j]);
   }
}

回报:

0 3 4 1 5 4 3 1 3 3

如何做到这一点?

【问题讨论】:

  • Floor,转换成整数,你有你的指数?
  • 你写的代码有什么问题?
  • @AllanWind 我想使用另一个大小为 5 的表来存储大小为 10 的表的值。例如,此示例的另一个表应该是 [1,2,3,2,1]
  • 你在间隔 2 中没有温度,所以我认为你的示例数据是错误的(除非我错过了什么)。请参阅下面的答案:

标签: c


【解决方案1】:

您创建一个温度计数组,并在对它们进行计数时使用间隔对数组进行索引:

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

#define LEN(a) sizeof(a) / sizeof(*a)

int main() {
    double tabledegrees[10]={0.2,3.4,4.3,1.2,5.6,4.5,3.8,1.5,3.4,3.7};
    size_t thermometers[5] = {0};
    for (size_t i=0; i < LEN(tabledegrees); i++)
        thermometers[(int) floor(tabledegrees[i])]++;
    for (size_t i=0; i < LEN(thermometers); i++)
        printf("%zu: %zu
", i, thermometers[i]);
}

这是示例输出:

0: 1
1: 2
2: 0
3: 4
4: 2

【讨论】:

  • 非常感谢。有没有办法在没有指针的情况下做到这一点?
  • 哪些指示以及您为什么关注这些指示?
  • 我指的是*表度
  • 我调整了使用宏的答案。您可以对数组长度进行硬编码,但这是一种更好的方法。
  • 非常感谢。非常有用的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-22
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
相关资源
最近更新 更多