C语言程序设计笔记--循环控制(中国大学MOOC翁凯)

    科技2026-02-14  19

    while循环

    do-while循环

    for循环

    for(循环变量类型 循环变量名称 ; 循环条件 ; 循环体语句)

    1.猜数游戏

    #include <stdio.h> int main() { int number = rand()%100+1; int count = 0; int a = 0; printf("我已经想好了一个1到100之间的数。"); do { printf("请猜这个1到100之间数:"); scanf("%d", &a); if ( a > number ) { printf("你猜的数大了。"); } else if ( a < number ) { printf("你猜的数小了。"); } count ++; } while (a != number); printf("太好了,你用了%d次就猜到了答案。\n", count); return 0; }

    2.求平均数

    #include <stdio.h> int main() { int sum = 0; int count = 0; int number; scanf("%d", &number); while ( number != -1 ) { sum += number; count ++; scanf("%d", &number); } double dsum = sum; printf("The average is %f.\n", dsum / count); return 0; }

    3.整数求逆

    #include <stdio.h> int main() { 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); return 0; }

    4.break VS continue

    break:跳出循环continue:跳过循环这一轮剩下的语句,进入下一轮两者只适用于他们所在的那层循环

    5.凑硬币

    如何用1角,2角和5角凑出10元以下的金额

    接力break

    goto + xxx

    6.分解整数输出

    #include <stdio.h> int main() { int x; scanf("%d", &x); int mask = 1; int t = x; do{ t /= 10; mask *= 10; } while ( t > 9 ) ; do{ int d = x/mask; printf("%d",d); if(mask > 9){ printf(" "); } x %= mask; mask /= 10; }while(mask>0); return 0; }

    7.求两数的最大公约数

    #include <stdio.h> int main() { int x,y,t; scanf("%d %d", &x,&y); while( y != 0){ t = x % y; x = y; y = t; } printf("gcd=%d\n",x); return 0; }
    Processed: 0.012, SQL: 9