I am trying to convert a floating point number to an integer, but it seems like the conversion is not working properly.
I am using the math library to calculate the power of 10 based on the number of varargs, where the first argument is the number of arguments followed by the varargs.
int charsToIntValue(int argc, ...) {
int multiplier = (int) pow(10, argc - 1);
va_list argp;
va_start(argp, argc);
Serial.println(multiplier);
...
va_end(argp);
}
For some reason, multiplier
is always stored as 1 less than the actual result.
e.g. If charsToIntValue(4, 1, 2, 3, 4)
is executed, the multiplier is stored as 999 rather than 1000. However, when it is printed as a float, it does show 1000.00. And whenever I change it to a constant ((int) pow(10, 3)
) it works fine, returning 1000.
I've tired storing the value of argc into a local variable but that didn't seem to change anything.
Full project is here for context: https://github.com/Pyrodron/charger-destination-board
File in question is charger-destination-board.ino; lines 32 to 51
charsToIntValue
doesn't show me what you're talking about. I don't think this has anything strictly to do with variadic function support. Nor Arduino. I will just add thatpow(10, argc - 1);
could be better written as a small function that takes anint
, returns anint
, and consists of a switch statement with nofloat
at all.pow()
returns a float. If yes, that that behavior seems normal. Floats can only save an aproximation of the wanted number. The actual float value, that is calculated might be something like 999.99. When you them convert to an int, the digits behind the decimal point get thrown away, leaving 999. Thats something, that you would need to accept, when you want to work with floats. And thats one reason, why it is often better, to just use an integer representation.math.h
library. It works now!