Determine the number of bits
Subject requirements
The program needs to read in a non-negative integer, and then output the number of digits of the integer. Such as 352, output 3.
Problem-solving ideas
The given number/10, that is, remove the rightmost number until the result is 0.
Code
while loop
#include<stdio.h>
int main(){
int x;
int n=0;
scanf("%d",&x);
n++;
x /=10;
**// a/=b等价于a=a/b
//while循环前加n++ x/10的目的是解决0的情况**
while(x>0){
n++;
x /=10;
}
printf("%d\n",n);
return 0;
}
do while loop
#include<stdio.h>
int main(){
int x;
int n=0;
scanf("%d",&x);
do{
n++;
x /=10;
}while(x>0);
printf("%d\n",n);
return 0;
}
Code summary
Do-while does not check when entering the loop, but checks whether the loop meets the conditions after executing a round of loop, and continues the loop if it is satisfied, but jumps out if it is not satisfied.
While is to first judge whether the condition is met, and then enter the loop body, after the loop, the condition is established and continue to loop until the condition is not met and exit the loop.
Difference: judgment condition, while before, do-while after
while may not do it again, do while will do it anyway
do while and while flow chart
Note: There must be a chance to change the conditions in the circulation body , otherwise the circulation may be stuck.