C语言中的循环(while 与 dowhile)(案例代码-逢7空格;三位数,各个位上的数字的立方和等于本数字)

    科技2022-09-05  104

    C语言中的循环(while 与 do while)

    1、whlie

    语法: while循环:

    while(条件判别表达式) { 循环体. }

    只要是满足条件判别表达式就执行循环体。(没有次数限制)

    案例代码: 要求: 敲7:1–100数数, 逢7和7的倍数,敲桌子。

    7的倍数: num % 7 == 0

    个位含7: num % 10 == 7

    十位含7: num / 10 == 7

    #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <time.h> int main() { int num = 1; while (num <= 100) { if ((num % 7 == 0) || (num % 10 == 7) || (num / 10 == 7)) // 个位、10位、7的倍数 { printf("敲桌子\n"); } else { printf("%d\n", num); } num++; // 递增 } }

    2、do while

    语法:

    无论如何先执行循环体一次。然后在判断是否继续循环。

    do { 循环体 } while (条件判别表达式);

    代码案例: 一个三位数。各个位上的数字的立方和等于本数字。

    100 – 999

    int num = 100;

    个位数: int a = num % 10; aaa;

    十位数: int b = num / 10 % 10;

    百位数: int c = num / 100;

    #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <time.h> int main() { int a, b, c; int num = 100; do { a = num % 10; // 个位 b = num / 10 % 10; // 十位 c = num / 100; // 百位 if (a*a*a + b * b*b + c * c*c == num) { printf("%d\n", num); } num++; } while (num < 1000); }

    这两个代码里面要注意怎样求一个数的百位、十位、个位。

    Processed: 0.013, SQL: 9