c#返回风力等级

本文最后更新于:1 年前

引言

最近对接了风向传感器,需要根据风速计算风力等级

这个问题其实就是数值分段

解决方案

风力等级取自百度百科:风力等级

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/// <summary>
/// 风力等级
/// </summary>
public static class WindPower
{
/// <summary>
/// 风力等级定义 :https://baike.baidu.com/item/%E9%A3%8E%E5%8A%9B%E7%AD%89%E7%BA%A7/8477486
/// </summary>
public static List<PowerRange> PowerDefined = new List<PowerRange>()
{
new PowerRange(0.0, 0.3),
new PowerRange(0.3, 1.6),
new PowerRange(1.6, 3.4),
new PowerRange(3.4, 5.5),
new PowerRange(5.5, 8.0),
new PowerRange(8.0, 10.8),
new PowerRange(10.8, 13.9),
new PowerRange(13.9, 17.2),
new PowerRange(17.2, 20.8),
new PowerRange(20.8, 24.5),
new PowerRange(24.5, 28.5),
new PowerRange(28.5, 32.7),
new PowerRange(32.7, 37.0),
new PowerRange(37.0, 41.5),
new PowerRange(41.5, 46.2),
new PowerRange(46.2, 51.0),
new PowerRange(51.0, 56.1),
new PowerRange(56.1, 61.3),
new PowerRange(61.3, -1),
new PowerRange(69.4, -1)
};
/// <summary>
/// 返回指定风速(单位m/s)的风力等级
/// </summary>
/// <param name="speed"></param>
/// <returns></returns>
public static int GetWindPower(double speed)
{
return GetIndexInRange(PowerDefined, speed);
}
/// <summary>
/// 从 指定的范围中返回找到的序号
/// </summary>
/// <param name="ranges"></param>
/// <param name="value"></param>
/// <returns></returns>
public static int GetIndexInRange(IList<PowerRange> ranges, double value)
{
int min = 0;
int max = ranges.Count - 1;

while (min <= max)
{
int mid = (min + max) / 2;
double comparison = ranges[mid].CompareTo(value);
if (comparison == 0)
{
return mid;
}

if (comparison < 0)
{
min = mid + 1;
}
else if (comparison > 0)
{
max = mid - 1;
}
}

return min;
}
}

public class PowerRange : IComparable<PowerRange>
{
private readonly double bottom; // Add properties for these if you want
private readonly double top;

public PowerRange(double bottom, double top)
{
this.bottom = bottom;
this.top = top;
}

public int CompareTo(PowerRange other)
{
if (bottom < other.bottom && top < other.top)
{
return -1;
}
if (bottom > other.bottom && top > other.top)
{
return 1;
}
if (bottom == other.bottom && top == other.top)
{
return 0;
}
throw new ArgumentException("Incomparable values (overlapping)");
}

/// <summary>
/// Returns 0 if value is in the specified range;
/// less than 0 if value is above the range;
/// greater than 0 if value is below the range.
/// </summary>
public int CompareTo(double value)
{
if (value < bottom)
{
return 1;
}
if (value > top)
{
return -1;
}
return 0;
}
}

调用非常简单:

WindPower.GetWindPower(Convert.ToDouble(windSpeed))


c#返回风力等级
http://blog.wangshuai.app/2023-01-09-.Net返回风力等级/
作者
王帅
发布于
2023年1月9日
许可协议