-
Notifications
You must be signed in to change notification settings - Fork 0
/
Round_by_0_5_steps.cs
57 lines (40 loc) · 1.15 KB
/
Round_by_0_5_steps.cs
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
using System;
namespace CodingChallenges;
[TestClass]
public class Round_by_0_5_steps {
/*
Round by 0.5 steps
Round any given number to the closest 0.5 step
I.E.
solution(4.2) = 4
solution(4.3) = 4.5
solution(4.6) = 4.5
solution(4.8) = 5
Round up if number is as close to previous and next 0.5 steps.
solution(4.75) == 5
solution(45.5) = 45.0
*/
[TestMethod]
public void Main() {
Assert.AreEqual(4, Solution(4.2));
Assert.AreEqual(4.5, Solution(4.4));
Assert.AreEqual(4.5, Solution(4.6));
Assert.AreEqual(5, Solution(4.8));
Assert.AreEqual(4, Solution_v2(4.2));
Assert.AreEqual(4.5, Solution_v2(4.4));
Assert.AreEqual(4.5, Solution_v2(4.6));
Assert.AreEqual(5, Solution_v2(4.8));
}
public static double Solution(double n) {
double t = Math.Truncate(n);
double d = n - t;
double dRounded = d switch {
<= 0.25 => 0d,
< 0.75 => 0.5d,
_ => 1d
};
return t + dRounded;
}
public static double Solution_v2(double n) =>
Math.Round(n * 2) / 2;
}