英文:
Javascript screen size with condition
问题
这可能听起来很简单,但我在数学方面不太擅长。我想要获取满足以下条件的x的值:
- 随机变量x必须大于半径
- 随机变量x必须小于(innerWidth - 半径)
var x = Math.random() * innerWidth;
var radius = 20;
有人可以帮助我吗?我相信这更多地涉及数学而不是我的编程技能。
[1] 图像卡在屏幕上:https://i.stack.imgur.com/Ib1km.png
英文:
This may sound easy but i am weak in math. I would like to get the value of x that must follow the condition
-
The randomised variable x must be larger than radius
-
The randomised variable x must be less than (innerWidth - radius)
var x = Math.random() * innerWidth ;
var radius = 20;
Can someone pls help me. I am sure it is more of a mathematics than my coding skills.
[enter image description here][1]
[1]Image Stuck at the screen : https://i.stack.imgur.com/Ib1km.png
答案1
得分: 0
Math.random()
会给你一个在 0 和 1 之间的随机值。
所以,Math.random() * n
会给你一个在 0 和 n 之间的随机值。
由于你需要在 radius
和 innerWidth - radius
之间获得随机值,我们将在 0 和 innerWidth - radius * 2
之间获取随机值,然后再加上 radius
,这将给我们在 radius
和 innerWidth - radius
之间的随机值。对吗?
所以,你需要的是:
var x = Math.random() * (innerWidth - 2 * radius) + radius;
英文:
Math.random()
gives you a random value between 0 and 1.
So, Math.random() * n
gives you a random value between 0 and n.
Since you need random values between radius
and innerWidth - radius
, we'll get the random values between 0 and innerWidth - radius * 2
and then add radius
to it, which will give us random values between radius
and innerWidth - radius
. Right?
So, what you need is:
var x = Math.random() * (innerWidth - 2 * radius) + radius;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论