do-while循环↓ while循环↓
数数位
运用成while
#include <stdio.h>
int main()
{
int x;
int n=0;
scanf("%d",&x);
n++;
x /= 10;
while ( x> 0){
n++;
x /= 10;
}
printf("%d\n",n);
return 0;
}
游戏名称1:
设计思路:
rand()//随机数
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(0));
int a = rand();
printf("%d\n",a);
return 0;
}
%100:x%n的结果是【0,n-1】的一个整数
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(0));
int number = rand()%100+1;
int count = 0;
int a = 0;
printf("我已经想好了一个1到100之间的数。");
do{
printf("请猜这个1到100之间数:");
scanf("%d",&a);
count ++;
if( a < number ){
printf("你猜的数大了。");
}else if ( a < number ){
printf("你猜的数小了");
}
}while ( a != number);
printf("太好了,你用了%d次就猜到了答案。\n",count);
return 0;
}
循环运用:算平均数
#include <stdio.h>
int main()
{
int number;
int sum = 0;
int count = 0;
do{
scanf("%d",&number);
if( number != -1){
sum += number;
count ++;
}
}while( number != -1;)
printf("%f\n",1.0 * sum/count);
return 0;
}
二次判断改一次判断:
#include <stdio.h>
int main()
{
int number;
int sum = 0;
int count = 0;
scanf("%d",&number);
while( number != -1){
sum += number;
count ++;
scanf("%d",&number);
}
printf("%f\n",1.0 * sum/count);
return 0;
}
循环应用:循环计算
// log2x
#include <stdio.h>
int main()
{
int x;
int ret = 0;
// scanf("%d",&x);
x = 128;
int t = x;
while( x > 1){
x /= 2;
ret ++;
}
printf("log2 of %d is %d.", t, ret);
return 0;
}
计数循环倒计时:
#include <stdio.h>
int main()
{
int n = 100;
while( n >= 0){
printf("%d\n",n);
n--;
}
printf("发射!\n");
return 0;
}
整数求逆:
#include <stdio.h>
int main()
{
int x;
scanf("%d",&x);
int dight;
int ret = 0;
while( x > 0){
dight = x%10;
//printf("%d\n",dight);
ret = ret*10 + dight;
printf("x=%d,dight=%d,ret=%d\n",x,dight,ret);
x /= 10;
}
printf("%d",ret);
return 0;
}