Hi all,
First post of someone just starting with Arduino and C, so maybe bit of a newbie question:
I have a power function in my code that calculates 2 to the power of a variable (2^i). The outcome is a float. This part works fine. However, when I convert that float to a int for further use, it subtracts 1 from it in most cases (when i > 2). This is clear in my serial output:
2^0 = 1.00 which is rounded off to: 1
2^1 = 2.00 which is rounded off to: 2
2^2 = 4.00 which is rounded off to: 3
2^3 = 8.00 which is rounded off to: 7
2^4 = 16.00 which is rounded off to: 15
2^5 = 32.00 which is rounded off to: 31
2^6 = 64.00 which is rounded off to: 63
2^7 = 128.00 which is rounded off to: 127
2^8 = 256.00 which is rounded off to: 255
So from i >=3, the integer rounds the float off with a -1 operation, it seems. Anyone know why this is? Below is the code that generated this serial output.
float outcome = 0;
int outcomeRounded = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
for (int i=0; i<=8; i++) {
outcome = (pow(2, i));
outcomeRounded = outcome;
Serial.print("2^");
Serial.print(i);
Serial.print(" = ");
Serial.print(outcome);
Serial.print(" which is rounded off to: ");
Serial.println(outcomeRounded);
}
delay(200000);
}