Asked by oded rupin
I have a general question. i was given a task to write a c code which gets an integer number as an input and prints the number of digits the number has.
I have written a function that does it, but the problem is whenever the integer number is n>=100, the program gets stuck.
can someone tell me what i did wrong, or rather how could i make it more efficint.
my code is
# include <stdio.h>
int get_nums(int n) //funtction that gets an integer num and returns how many digits it has
{
int nums,p,q;
nums=1;
p=10;
q=n/p;
while(n/p!=0)
{
n=q;
nums++;
}
return nums;
}
main()
{
int n,nums;
printf("enter an integer number \n n=");
scanf("%d",&n);
nums=get_nums(n);
printf("\n nums= %d",nums);
}
I have written a function that does it, but the problem is whenever the integer number is n>=100, the program gets stuck.
can someone tell me what i did wrong, or rather how could i make it more efficint.
my code is
# include <stdio.h>
int get_nums(int n) //funtction that gets an integer num and returns how many digits it has
{
int nums,p,q;
nums=1;
p=10;
q=n/p;
while(n/p!=0)
{
n=q;
nums++;
}
return nums;
}
main()
{
int n,nums;
printf("enter an integer number \n n=");
scanf("%d",&n);
nums=get_nums(n);
printf("\n nums= %d",nums);
}
Answers
Answered by
Steve
n and p never change!
You need to do something like
get_nums(n) {
if n==0 return 1;
nums=0
while (n!=0) {
n /= 10;
nums++;
}
return nums;
}
Since get_nums is call-by-value, the calling values does not get changed.
You need to do something like
get_nums(n) {
if n==0 return 1;
nums=0
while (n!=0) {
n /= 10;
nums++;
}
return nums;
}
Since get_nums is call-by-value, the calling values does not get changed.
Answered by
oded rupin
Thank you I didn't noticed that was my problem now it works.
There are no AI answers yet. The ability to request AI answers is coming soon!
Submit Your Answer
We prioritize human answers over AI answers.
If you are human, and you can answer this question, please submit your answer.