From chatGPT3.5 # 四舍五入到最接近的整数 round_half_up <- function(x) { ifelse(x >= 0, floor(x + 0.5), ceiling(x - 0.5)) } # 示例 result1 <- round_half_up(0.5) # 结果为 1 result2 <- round_half_up(0.49) # 结果为 0 print(result1) print(result2) sunleilucky 发表于 2023-11-28 15:21
代码越简单越好。
return num % 1 >= 0.5 ? Math.ceil(num) : Math.floor(num)
谢谢!
看chatgpt给我的答案。
custom_round <- function(x) { ifelse(x >= 4.5, ceiling(x), floor(x)) }
# Examples rounded_value_1 <- custom_round(0.5) # Results in 1 rounded_value_2 <- custom_round(0.49) # Results in 0 rounded_value_3 <- custom_round(4.5) # Results in 5 rounded_value_4 <- custom_round(4.49) # Results in 4