Math is hard, let's try programming!We've played around with printing out phrases, but it turns out we can also print out numbers pretty easily too. Try out this sketch on your Arduino: We've seen that if you use a quoted line of text as argument to println function, it will display the quoted text. If you don't include the quotes your Arduino sees the argument as a variable and the println will look up what the variable contains and print its value instead. Serial.println(a); So in this case we would not see a in the Serial Monitor, but instead we would see 3. Note that we're using 2 different serial functions here, the original println and now also print. The print function is just like println except it does not print out a "carriage return" at the end, starting a new line. Serial.print("a = "); Serial.println(a); So, a = would print in the Serial Monitor and then be followed by 3 on the same line. You can experiment with changing the print's to println's and looking at the Serial Monitor to see how it looks different. It turns out that the Arduino is smart enough to also do math when asked: Serial.println(a + b); In this case, the Arduino looks at what the argument to println is, and finds it's actually a calculation. It looks up what a is (3) and what b is (10) and then adds them together (+). It then uses that as the value to send to println. Serial.print("a * c = "); // multiply Serial.println(a * c); You may have noticed that for multiplication we used an asterisk instead of an x. Since x is a letter computers would never know when you want the letter and when you intend to multiply so instead we use an askerisk as our multiplication symbol. Serial.print("b / a = "); // divide Serial.println(b / a); When we look at the results for b / a in Serial Monitor we see the result isn't very precise. So far we've only been working with integers, which if you recall, are whole numbers. If the variables we are calculating with are integers then our answer will be an integer as well. If there are decimals they will simply be dropped from the result. We can fix our decimal problem by changing our variable types when we declare them. We can use float instead of int. Floats can have decimals. You may be wondering why we don't use float all the time. We will save that discussion for a little later. For now change the variable declaration portion of your sketch to be: float a = 3; float b = 10; float c = 20; When you upload and run your sketch you'll notice that everything has decimals now and we can get an actual answer to "b / a". |