圆形双至最接近10 [英] Round Double to closest 10

查看:96
本文介绍了圆形双至最接近10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,如果数字是8.0,然后循环到10.
如果数字是2.0回合到0。



我不知道从哪里开始。你会建议什么?

解决方案

你可以使用 round()函数(将浮点数
加到最接近的整数值),并应用10的比例因子:

  func roundToTens(x:Double) - > Int {
return 10 * Int(round(x / 10.0))
}

示例用法:

  print(roundToTens(4.9))// 0 
print(roundToTens(15.1)) // 20

在第二个例子中, 15.1 除以十( 1.51 ),四舍五入( 2.0 ),
转换为整数( 2 ),再乘以10( 20 )。


I would like to round a Double to the closest 10.

For example if the number is 8.0 then round to 10. If the number is 2.0 round it to 0.

I am not sure where to start with this. What would you suggest?

解决方案

You can use the round() function (which rounds a floating point number to the nearest integral value) and apply a "scale factor" of 10:

func roundToTens(x : Double) -> Int {
    return 10 * Int(round(x / 10.0))
}

Example usage:

print(roundToTens(4.9))  // 0
print(roundToTens(15.1)) // 20

In the second example, 15.1 is divided by ten (1.51), rounded (2.0), converted to an integer (2) and multiplied by 10 again (20).

这篇关于圆形双至最接近10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆