Issue
My assignment is to create a function that displays the number entered as a parameter. The function has to be able to display all possible values within an int
type variable. write()
is the only allowed function.
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putnbr(int nb)
{
if (nb < 0)
{
ft_putchar('-');
ft_putchar(-nb + '0');
}
if ( nb > 0)
{
ft_putchar(nb + '0');
}
}
I wrote this but obviously it doesn't work for integers that have 2 or more digits, how can I display them as a string?
Solution
write is the only allowed function.
A more general solution would use a loop to handle 10s, 100s, etc. Try dividing by the largest power-of-10 and then 1/10 of that, etc.
To handle all int
is a little tricky. Beware of code that does -INT_MIN
as that is undefined behavior (UB). Instead, use the negative side of int
after printing the sign as there are more negative int
than positive ones.
#if INT_MAX == 2147483647
# define INT_POW_MAX (1000 * 1000 * 1000)
#elif INT_MAX == 32767
# define INT_POW_MAX (10 * 1000)
#else
// For greater portability, additional code needed
# error "TBD code"
#endif
void ft_putnbr(int nb) {
if (nb < 0) {
// Do not use -nb as that is UB when nb == INT_MIN
ft_putchar('-');
} else {
nb = -nb;
}
// At this point, nb <= 0
int pow10n = -INT_POW_MAX;
// Skip leading 0 digits.
while (pow10n < nb) {
pow10n /= 10;
}
// Print the rest.
do {
int q = pow10n ? nb/pow10n : nb;
ft_putchar(q + '0');
nb -= q*pow10n;
pow10n /= 10;
} while (pow10n);
}
Passes test harness.
Answered By - chux - Reinstate Monica Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.