I tried to calculate the value of ThisRampTime in an if statement (without declaring it as variable, just the calculation) for doing a delay with millis(). But it always returned 0 and my if statement was executed instantly.
Then I assumed maybe it overflows some variable in the If function and calculated it outside of the if statement. It also returned 0.
Then I assumed it migh be possible float is needed so I changed the int declaration to float But it still returns 0! Even with brackets around the calculation....
WHY? Float should be big enough as far as I looked up.
And you should notate it 65280000L if its a long constant, 6.528e7 if its a float constant.
The default int type is 16 bit which is not able to represent the number 65280000
You need to declare constants long if you want the operator to be long:
void setup()
{
Serial.begin (115200) ;
int a = 1000 ;
long b = a * 1000 ; // wrong
long c = b / 100000 ; // wrong
Serial.println (a) ;
Serial.println (b) ;
Serial.println (c) ;
b = a * 1000L ; // correct constants, the right * and / operations are used
c = b / 100000L ;
Serial.println (b) ;
Serial.println (c) ;
}
void loop()
{}
@MarkT and @Gorkde as well, that's ONLY because you try to do math that will result in something bigger then an int. But no need to do it on the literal itself if it's stored in a long and is bigger then int.
b = a * 1000L ; // correct constants, the right * and / operations are used
c = b / 100000 ;
Works just fine as well.
Same as
long myLong = 123456;
Serial.print(myLong);
Works fine as well, 123456 is not cropped to an int.
Aka, if the literal is bigger then the default int it's already promoted to long. So you only need to explicit promote a literal (or variable for that matter) if it's used in math that has a possible outcome that's bigger then the size of the variables OR literals used in the math. In your example for example, if a was defined a long there was no need to promote the literal.
Or another "trick" is to use the output variable in the math
septillion:
But do know you loose accuracy in the esteems of a float (very large or very small).
Floats have exactly the same number of significant figures no matter what their magnitude.
Gorkde:
Bulldog: Thats what I thought as well and why I tried using float.
You only declared the variable storing the result as a float. All of the values used to perform the calculation are integers, so it will use integer arithmetic all the way up to the end, then the assignment converts it to a float. If you want to perform floating point math, you need to declare the variables as floats or convert them to floats when you perform the calculation.