The variable passed to the function is not set to the value assigned to it
To return the i-th digit to the left of a given number, I created this function:
int ith(unsigned long x, int i)
{
int count=0;
unsigned long y = x;
do
{
y /= 10;
count++;
} while (y > 0);
if (i > count)
return -1;
count -= i;
while (count > 0)
{
x /= 10;
count--;
}
return x % 10;
}
However, when the input for the function is 2.2. It took a long time for the function to be Finnish; so I looked in the debugger and noticed that count==54353453
and count
never get 0
which I assigned to it.
EDIT Here the rest of my code, as some of the suggested ones, might be the source of this error.
int main()
{
int x, i,result;
do
{
printf("Enter a number and the digit you want to retrieve.\nEnter a negative number to exit\n");
scanf("%ul %d", &x, &i);
if (x<0)
{
printf("Operation Aborted.. Exiting....\n");
break;
}
else
{
result = ith(x, i);
if (result == -1)
{
printf("Error: There are no such amount of digits to retrieve from that location\n");
continue;
}
printf("The %dth digit of the number %ul is %d\n", i, x, result);
}
} while (x >= 0);
}
source to share
This line
scanf("%ul %d", &x, &i);
uses the wrong specifier to scan to x
.
As x
determined int
, it should be
scanf("%d %d", &x, &i);
or you define x
how unsigned long
, then it should be
scanf("%lu %d", &x, &i);
Same problem here:
printf("The %dth digit of the number %ul is %d\n", i, x, result);
source to share