I have the following sample code. It is supposed to do a simple calculation and give me the result on the serial monitor. When I do the exact same calculation with my calculator I get 46 but here I get 44. I tried similar calculations and they all gave me a result 2 numbers lower than the real result. The only exception was when "n" was 0 and "d" was 1 so "fraction" = 0. Why does this happen? Apologies if this question has been reposted, couldn't find an answer.
#include <Wire.h>
void setup() {
Serial.begin(9600);
Serial.println("OK");
int n = 19;
int d = 25;
int a = 25;
int m = 14;
long fraction = n/d;
long output = ((25*(a+fraction))/(m));
Serial.println((long)output);
}
void loop() {
}
Is this a homework exercise? If it is, I suggest that you not use floats.
What I am guessing you are being tested on is your ability to use algebra to rearrange the problem so as to avoid the need for floats.
Example: How much is two-thirds of 90?
Incorrect solution: (2/3)*90 which gives 0
Correct solution: (2*90)/3 which gives 60
Explanation: Algebraically, (a/b)*c is the same as (a*c)/b, so if we can't trust a/b to be evaluated "properly", we have a workaround.
chummer1010:
Are you saying that's what the Arduino computes?
According to the definition of the C++ language, if you do division with two integer valued quantities, then the result is an integer and the remainder is truncated.
Your variable 'fraction' is of type long. This means that it holds whole numbers.