啊哈c语言——逻辑挑战6:奔跑的小人

发布时间:2024年01月01日

首先我们来设计这个小人:

????????将这个小人身体的三部分分为3行来分别表示:

第1行用一个大写字母O表示小人的脑袋。

第2行用左尖括号表示小人的右手,用大写字母H表示小人的身 体,用右尖括号>表示小人的右手。

第3行用两个大写字母I表示小人的两条腿,为了对称,两个大写字 母I之间用一个空格隔开。

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
    printf(" O\n");
    printf("<H>\n");
    printf("I I\n");
    system("pause");
    return 0;
}

现在我们让小人动起来。首先回顾一下让字母奔跑起来的代码:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
    int a, b;
    a=0;
    while(a<=2)
    {
        system("cls");
        b=1;
        while(b<=a)
        {
            printf(" ");
            b=b+1;
        }
        printf("H");
        Sleep(1000);
        a=a+1;
    }
    system("pause");
    return 0;
}

我们把上面代码中的

改为:

完整的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
    int a, b;
    a=0;
    while(a<=2)
    {
        system("cls");
        b=1;
        while(b<=a)
        {
            printf(" ");
            b=b+1;
        }
        printf(" O\n");
        printf("<H>\n");
        printf("I I\n");
        Sleep(1000);
        a=a+1;
    }
    return 0;
}

????????运行后你会发现,只有小人的脑袋往右边移动,身体和腿呆在原地,这是为什么?

????????分析后我们发现,让小人往右移动主要通过在小人的左边不停地打印空格来实现。但是我们只在第1行的左边打印了空格,在第2行和第3 行都没有打印空格的语句。因此我们要将打印空格的while循环再复制 一遍分别放在printf("\n");和printf("I I\n");前面,完整的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
    int a, b;
    a=0;
    while(a<=2)
    {
        system("cls");
        b=1;
        while(b<=a)
        {
            printf(" ");
            b=b+1;
        }
        printf(" O\n");
        b=1;
        while(b<=a)
        {
            printf(" ");
            b=b+1;
        }
        printf("<H>\n");
        b=1;
        while(b<=a)
        {
            printf(" ");
            b=b+1;
        }
        printf("I I\n");
        Sleep(1000);
        a=a+1;
    }
    system("pause");
    return 0;
}

????????怎么样,小人是不是奔跑起来啦!

????????如果希望小人跑得更远,我们只需把while(a<=2)改为 while(a<=80)。如果让小人跑得更快一点,我们之前已经学习过,只 需把Sleep(1000);改为较小的值就可以了,越小越快,例如,改为 Sleep(100);赶快试一试吧。

文章来源:https://blog.csdn.net/weixin_43349327/article/details/135326960
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。