/* 24/07/2021 mathmaticsv4 Division Understand the issues with division of integers. learn how to use a float. Arduinos do NOT like floats, they use a lot of processor time compared to whole numbers. */ int q; int w; int myAnswer; float myFloat; void setup() { // Serial.begin(9600) starts serial communication. 9600bps bits per second = 1200 characters per second Serial.begin(9600); //Send script name Serial.println("mathematicsv4..."); //this will print a blank line Serial.println(" "); } void loop() { if (q < 1) { //Example 1 //add 1 to the value of q so the if statement will fail next time round q++; Serial.print("q = "); Serial.println(q); //Simple addition Serial.println("Simple division"); for (w = 0; w < 10; w++) { // the symbol for division is / myAnswer = w / q; Serial.print(" w ="); Serial.print(w); Serial.print(" myAnswer ="); Serial.println(myAnswer); } //Example 2 //change the value of q to 10 q = 10; //Notice that an integer cannot have a decimal point Serial.println("Simple division...all the results are rounded down."); Serial.print("q = "); Serial.println(q); for (w = 0; w < 31; w++) { myAnswer = w / q; Serial.print(" w ="); Serial.print(w); Serial.print(" myAnswer ="); Serial.println(myAnswer); } //Example 3 //change the value of q to 10 q = 10; //Notice that an integer cannot have a decimal point //helps with the issue of dividing and then multiplying Serial.println("Simple division...multiplying by 100 to use a whole number."); Serial.print("q = "); Serial.println(q); for (w = 0; w < 31; w++) { myAnswer = w * 100 / q; Serial.print(" w ="); Serial.print(w); Serial.print(" myAnswer ="); Serial.println(myAnswer); } //Example 4 //change the value of q to 10 q = 10; //Using a float to get a decimal point Serial.println("Simple division...Using a float"); Serial.print("q = "); Serial.println(q); for (w = 0; w < 31; w++) { //because the division is between two integers there is no decimal value even when we save the result as a float. myFloat = w / q; Serial.print(" w ="); Serial.print(w); Serial.print(" myFloat ="); Serial.println(myFloat); } //Example 4 q = 10; //Using a flat to get a decimal point Serial.println("Simple division...Using a float"); Serial.print("q = "); Serial.println(q); for (w = 0; w < 31; w++) { myFloat = float(w) / float(q); Serial.print(" w ="); Serial.print(w); Serial.print(" myFloat ="); //Only prints to 2 decimal places by default Serial.print(myFloat); Serial.print(" myFloat to 4 decimal points =" ); Serial.println(myFloat,4); } } }