intmain() { 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("你猜的数大了。"); } elseif ( a < number ) { printf("你猜的数小了。"); } } while (a != number); printf("太好了,你用了%d次就猜到了答案。\n", count); return0; }
intmain() { 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); return0; }
等同于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<stdio.h>
intmain() { 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); return0; }
3.循环计算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<stdio.h>
intmain() { int x; int ret = 0; scanf("%d", &x); while ( x > 1 ) { x /= 2; ret ++; } printf("log2 of %d is %d.", x, ret); return0; }
等同于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<stdio.h>
intmain() { int x; int ret = 0; scanf("%d", &x); int t = x; while ( x > 1 ) { x /= 2; ret ++; } printf("log2 of %d is %d.", t, ret); return0; }
intmain() { int x; scanf("%d", &x); int digit; int ret = 0; while ( x > 0 ) { digit = x%10; ret = ret*10 + digit; x /= 10; } printf("%d", ret); return0; }