Please help me to create code that will do some conversion between two units of measure. They will measure the same thing (length, pressure, time, currency etc.) but will convert from one unit to another.
Making the constants float would make the intent more clear but is not required because of the way that the equation is arranged and is required to be evaluated under the specifications of C/C++.
vaj4088:
Making the constants float would make the intent more clear but is not required because of the way that the equation is arranged and is required to be evaluated under the specifications of C/C++.
I was talking also of "implicit" constant like in :
I do not understand implicit constant, but there are no parentheses so the calculation will be performed from left to right. If degC is double, then the 9 becomes 9.0, then the 5 becomes 5.0, then the 32 becomes 32.0 (and, of course, the calculations and the results are double).
I have shortcut some of the details but that is the gist of what happens.
vaj4088:
I do not understand implicit constant, but there are no parentheses so the calculation will be performed from left to right. If degC is double, then the 9 becomes 9.0, then the 5 becomes 5.0, then the 32 becomes 32.0 (and, of course, the calculations and the results are double).
I have shortcut some of the details but that is the gist of what happens.
I was thinking about this kind of problem (try it) :
void setup()
{
Serial.begin(2000000);
int degC = 20;
float degF;
float degF2;
degF = degC * 50 * 1000 ;
degF2 = degC * 50. * 1000. ;
Serial.println(degF);
Serial.println(degF2);
}
void loop() {
// put your main code here, to run repeatedly:
}
will be evaluated using (16-bit) int arithmetic and will have a rollover problem.
This
degF2 = degC * 50. * 1000. ;
has no such problem because the value from the variable degC will be upgraded to a double and thus all of the arithmetic will be performed as double and then downgraded to float for assignment to degF2. There is no rollover issue here.
Note that if the variable degC had been declared float or double, even the first expression would have worked well because EVERYTHING (values and arithmetic) would have been handled as double until the assignment to the float variable degF.
vaj4088:
Because the variable degC is declared int, this
degF = degC * 50 * 1000 ;
will be evaluated using (16-bit) int arithmetic and will have a rollover problem.
This
degF2 = degC * 50. * 1000. ;
has no such problem because the value from the variable degC will be upgraded to a double and thus all of the arithmetic will be performed as double and then downgraded to float for assignment to degF2. There is no rollover issue here.
Note that if the variable degC had been declared float or double, even the first expression would have worked well because EVERYTHING (values and arithmetic) would have been handled as double until the assignment to the float variable degF.