p5.js | int()函数
p5.js 中的int()函数用于将给定的布尔值、整数和浮点值转换为其整数表示形式。
句法:
int(ns)
或者
int(n, radix)
参数:此函数接受以下三种类型的参数:
- n:存放需要转换成整数的值。 n 的可能值是字符串、布尔值或数字。
- radix:存储数字转换成的小数部分。
- ns:它将不同类型的元素存储到数组中。
返回值:它返回转换后的整数表示。
以下程序说明了 p5.js 中的 int()函数:
示例 1:此示例使用 int()函数将输入值转换为其整数值。
javascript
function setup() {
// Creating Canvas size
createCanvas(600, 160);
}
function draw() {
// Set the background color
background(220);
// Initializing some strings
let Value1 = 12;
let Value2 = 12.5;
let Value3 = -7.9;
let Value4 = -6;
let Value5 = "6";
// Calling to int() function.
let A = int(Value1);
let B = int(Value2);
let C = int(Value3);
let D = int(Value4);
let E = int(Value5);
// Set the size of text
textSize(16);
// Set the text color
fill(color('red'));
// Getting integer representation
text("Integer representation of value 12 is: " + A, 50, 30);
text("Integer representation of value 12.5 is: " + B, 50, 60);
text("Integer representation of value -7.9 is: " + C, 50, 90);
text("Integer representation of value -6 is: " + D, 50, 110);
text("Integer representation of string '6' is: " + E, 50, 140);
}
javascript
function setup() {
// Creating Canvas size
createCanvas(600, 140);
}
function draw() {
// Set the background color
background(220);
// Initializing some values
let Value1 = true;
let Value2 = false;
let Value3 = "Geeks";
let Value4 = [12, 3.6, -9.8, true, false, "Geeks"];
// Calling to int() function.
let A = int(Value1);
let B = int(Value2);
let C = int(Value3);
let D = int(Value4);
// Set the size of text
textSize(16);
// Set the text color
fill(color('red'));
// Getting integer representation
text("Integer representation of value 'true' is: " + A, 50, 30);
text("Integer representation of value 'false' is: " + B, 50, 60);
text("Integer representation of value 'Geeks' is: " + C, 50, 90);
text("Integer representation of array of values are: " + D, 50, 110);
}
输出:
示例 2:此示例使用 int()函数将输入值转换为其整数值。
javascript
function setup() {
// Creating Canvas size
createCanvas(600, 140);
}
function draw() {
// Set the background color
background(220);
// Initializing some values
let Value1 = true;
let Value2 = false;
let Value3 = "Geeks";
let Value4 = [12, 3.6, -9.8, true, false, "Geeks"];
// Calling to int() function.
let A = int(Value1);
let B = int(Value2);
let C = int(Value3);
let D = int(Value4);
// Set the size of text
textSize(16);
// Set the text color
fill(color('red'));
// Getting integer representation
text("Integer representation of value 'true' is: " + A, 50, 30);
text("Integer representation of value 'false' is: " + B, 50, 60);
text("Integer representation of value 'Geeks' is: " + C, 50, 90);
text("Integer representation of array of values are: " + D, 50, 110);
}
输出:
注意:从上面的程序中,如果参数的值是数字,那么它以整数表示形式返回输出,对于 false 它返回 0,对于 true 它返回 1,对于字符串值,它返回 NaN,即不是数字。
参考: https://p5js.org/reference/#/p5/int