参考 Number

Number

一个可以是正数、负数或零的数字。

Number 数据类型用于描述位置、大小和颜色等值。数字可以是整数,如 20,也可以是十进制数,如 12.34。 例如,圆的位置和大小可以用三个数字来描述:

circle(50, 50, 20); circle(50, 50, 12.34);

数字支持基本的算术运算,并遵循标准的运算顺序:括号、指数、乘法、除法、加法和减法(PEMDAS)。 例如,我们通常使用算术运算符与 p5.js 的系统变量,这些变量都是数字:

// Draw a circle at the center. circle(width / 2, height / 2, 20); // Draw a circle that moves from left to right. circle(frameCount * 0.01, 50, 20);

以下是算术运算符的简要概述:

1 + 2 // Add 1 - 2 // Subtract 1 * 2 // Multiply 1 / 2 // Divide 1 % 2 // Remainder 1 ** 2 // Exponentiate

常见的是使用算术运算更新数字变量。例如,可以像这样更新对象的位置:

x = x + 1;

上面的语句使用 + 运算符将 x 的值变为 x + 1。 加法赋值运算符 += 表达了相同的意思:

x += 1;

以下是赋值运算符的简要概述:

x += 2 // Addition assignment x -= 2 // Subtraction assignment x *= 2 // Multiplication assignment x /= 2 // Division assignment x %= 2 // Remainder assignment

数字可以通过 relational operators 进行比较: &gt;&lt;&lt; code=""&gt;,<code>&gt;=</code>,<code>&lt;=&lt; code=""&gt;,<code>===</code>,和 <code>!==</code>。 例如,绘图的 <a href="/reference/p5/frameCount">frameCount</a> 可以用作计时器:<!--=<--></code><!--<-->

if (frameCount &gt; 1000) { text('Game over!', 50, 50); }

类似 frameCount &gt; 1000 这样的表达式,会得出一个 Boolean 值, 要么是 true,要么是 false。关系运算符的运算结果都是 Boolean 值。

2 &gt; 1 // true 2 &lt; 1 // false 2 &gt;= 2 // true 2 &lt;= 2="" true="" !="=" false="" &lt;="" code=""&gt; <p>获取更多关于比较和条件的信息,请参阅 <a href="/reference/p5/Boolean">Boolean</a>。</p> <p>注意:还有少一个 <code>=</code> 的 <code>==</code> 和 <code>!=</code> 运算符,不要使用它们。</p> <p>当某些情况出错时,数字表达式也可以产生特殊值:</p> <code> sqrt(-1) // NaN 1 / 0 // Infinity </code> <p><code>NaN</code> 值表示非数字 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN" target="_blank">Not-A-Number</a>。 计算或转换失败时,返回 <code>NaN</code>。 <code>Infinity</code> 是一个大于任何数字的值,它会出现在某些计算中。</p> <!--=-->

示例

Notice any errors or typos? Please let us know. Please feel free to edit src/core/reference.js and open a pull request!

相关参考