小编wp-*_*com的帖子

你如何在Python中舍入一个数字?

这个问题让我很难过.如何在Python中对数字进行综合?

我尝试了一些(数字),但它将数字向下舍入.例:

round(2.3) = 2.0 and not 3, what I would like
Run Code Online (Sandbox Code Playgroud)

我尝试了int(数字+ .5),但它再次将数字向下舍入!例:

int(2.3 + .5) = 2
Run Code Online (Sandbox Code Playgroud)

然后我尝试了一下(数字+ .5)但它在边缘情况下不起作用.例:

WAIT! THIS WORKED!
Run Code Online (Sandbox Code Playgroud)

请指教.

python floating-point integer rounding python-2.x

439
推荐指数
17
解决办法
70万
查看次数

在javascript中生成随机颜色的最佳方法?

在JavaScript中生成随机颜色的最佳方法是什么?不使用任何框架...

以下是我提出的几个解决方案:

function get_random_color() 
{
    var color = "";
    for(var i = 0; i < 3; i++) {
        var sub = Math.floor(Math.random() * 256).toString(16);
        color += (sub.length == 1 ? "0" + sub : sub);
    }
    return "#" + color;
}

function get_rand_color()
{
    var color = Math.floor(Math.random() * Math.pow(256, 3)).toString(16);
    while(color.length < 6) {
        color = "0" + color;
    }
    return "#" + color;
}
Run Code Online (Sandbox Code Playgroud)

有更好的方法吗?

javascript random

37
推荐指数
6
解决办法
7万
查看次数

在for循环中处理undefined?

假设我的代码如下:

const days = ['Monday', 'Tuesday'];

for (const day of days) {
  console.log(day);
}
Run Code Online (Sandbox Code Playgroud)

打印出"周一"和"周二".

如果由于某种原因,days未定义,那么我会收到运行时错误.

我可以通过输入如下代码来处理这个问题:

if (undefined == days) {
  // logic here
}
Run Code Online (Sandbox Code Playgroud)

对我来说,这看起来有点笨重.有没有办法让for ... of循环忽略未定义的值?基本上,将它视为零长度数组,因此for循环内部的逻辑不会执行,但它也不会抛出错误.

javascript

1
推荐指数
1
解决办法
84
查看次数