I’m trying (without much success) to write a short c++ function:
double digit(double x, int b, int d)
that returns the d-th digit in base-b expansion of the number x, which can be positive or negative, and can be a fraction. when d is negative, it should return the after-the-decimal-dot digits (its underfined for d=0 so say it returns 0 in that case).
For example:
const double x = 25.73;
for (int n = -5; n <= 5; n++)
cout<<digit(x,10,n)<<' ';
should print:
0
0
0
3
7
0
5
2
0
0
0
The function must use only loops, if, exp, pow, log, floor and ceil. i.e., without sprintf tricks etc.
Thanks!!!
EDIT: For simplicity, assume 2<=b<=10
EDIT: Please also avoid using mod, only pow-exp-log-floor-ceil based solutions
This seems to be the most straightforward implementation, and it seems to work just fine.
I changed the return type from
doubletointsince it doesn’t make sense to have a fraction in a digit. And it doesn’t return.for 0, because again that’s not a digit. The 0’th place value is the one’s place.Also this ignores the minus sign; you didn’t define the “base-b expansion” for negative numbers. You could adjust the function to return b’s complement notation or whatever.
By substituting
xyou can make this into one line, so it will satisfy the requirements forconstexpron platforms where the math functions areconstexpras well.