arduino / reference-en

Editable source for the Arduino Reference
https://www.arduino.cc/reference/en/
Other
165 stars 731 forks source link

Add an example code to abs() [CNT-1196] #841

Closed mkaivo closed 3 years ago

mkaivo commented 3 years ago

Hi, we got a request to add an example code of abs(). Could this work? It is a pretty straightforward function. See the Jira task here: https://arduino.atlassian.net/browse/CNT-1196

CLAassistant commented 3 years ago

CLA assistant check
All committers have signed the CLA.

mkaivo commented 3 years ago

I don't find this to be a useful demonstration of abs(). The result is most interesting when applied to negative numbers, but it will take a long time for a to overflow to a negative number. The mixture of int and float types is also odd.

If you want a standalone sketch, I would suggest something more straightforward like this:

void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ;  // wait for serial port to connect. Needed for native USB port only
  }
  int x = 42;
  Serial.print("The absolute value of ");
  Serial.print(x);
  Serial.print(" is ");
  Serial.println(abs(x));
  x = -42;
  Serial.print("The absolute value of ");
  Serial.print(x);
  Serial.print(" is ");
  Serial.println(abs(x));
}

void loop() {
}

or perhaps just a simple on-liner as is done for some of the other math functions: https://www.arduino.cc/reference/en/language/functions/math/max/#_example_code

Hi! I have updated the example sketch with your example. Thanks