判断四位数及以下的整数等级:
#include <stdio.h>
int main()
{
int x;
int n = 1;
scanf("%d", &x);
if (x > 999) {
n = 4;
}
else if (x > 99) {
n = 3;
}
else if (x > 9) {
n = 2;
}
else {
n = 1;
}
printf("%d\n", n);
return 0;
}
注意:
大于时,从高处往下判断,所以无需判断上限。例如:对于100,只需判断100>99,不用判断100<=999。因为如果>999的话已经被第一个条件拦截了,不会再传下来。
小于时,从低处往上判断。
任意正整数怎么办????
#include <stdio.h>//数正整数位数
int main()
{
int x;
int n;
scanf("%d", &x);
n++;
x /= 10;//x=x/10
while (x > 0) {
n++;
x /= 10;
}
printf("%d\n", n);
return 0;
}
while (x > 0) {
x /= 10;
n++;
}
//( )内是条件
//{ }内是循环体
注意!!:循环体内要有改变条件的机会,否则是死循环。