Description

Calculates the square of a number: the number multiplied by itself.

Syntax

Use the following function to compute the square of a number:

sq(x)

Parameters

The function admits the following parameter:

x: the input number. Allowed data types: any data type.

Returns

The function returns the square of the number. Data type: double.

Example Code

Calculate the square of x:

float x = 2.0;  

void setup() {
  Serial.begin(9600);

  double square = sq(x);

  Serial.print("The result is: ");
  Serial.println(square);
}

void loop() {
}

Notes and Warnings

Because of the way the sq() function is implemented, avoid using other functions inside the brackets, it may lead to incorrect results.

This code will yield incorrect results:

 int inputSquared = sq(Serial.parseInt()); // avoid this

Use this instead:

int input = Serial.parseInt();  // keep other operations outside the sq function
int inputSquared = sq(input);

See also