第六章 课本例题

6.1 键盘输入n,计算1+2+3+……+n的值。

(太简单了,略)

6.2 键盘输入n,计算n!的值。

(太简单了,略)

6.3 试编写一个程序,从键盘输入n,计算1~n之间所有数的阶乘。(迭代一次输出一个数即可)

(太简单了,略)

6.4 1!+2!+3!+……+n!=?

(太简单了,略)

扫描二维码关注公众号,回复: 5345880 查看本文章

6.5 演示嵌套循环

6.6 猜数游戏。用rand()生成随机数。用户猜一个数,会提示大了小了还是正确了。只给一次机会。

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int y,x=rand();
scanf("%d",&y);
    if(y==x)
    {
        printf("YES\n");
    }else
    {
        if(y>x)
        {
            printf("BIG\n");
            
        }else
        {
            printf("SMALL\n");
        }
    }
    
    return 0;
 } 

6.7 在6.6的基础上,直到用户猜对为止。

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int y,x=rand(),bl=0;
    while(bl==0){
     scanf("%d",&y);
    if(y==x)
    {
        printf("YES\n");
        bl=1;
        //break;
        //exit(0);
    }else
    {
        if(y>x)
        {
            printf("BIG\n");
            
        }else
        {
            printf("SMALL\n");
        }
    }
}
    return 0;
 } 

6.8 在6.7的基础上,只可以猜10次。

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int y,x=rand(),i=0;
    while(i<10){
     scanf("%d",&y);
    if(y==x)
    {
        printf("YES\n");
        break;
        //exit(0);
    }else
    {
        if(y>x)
        {
            printf("BIG\n");
            
        }else
        {
            printf("SMALL\n");
        }
    }
    i++;
}
    return 0;
 } 

6.9 在6.8的基础上清除错误输入。

(略)

6.10 猜完一个数后猜下一个数。

(略)

6.11 读入五个正整数,并显示它们。如果输入为负,则终止。(用goto和break分别来写)

goto:

#include<stdio.h>
int main()
{
    int index=0,x;
    while(index<5)
    {
        printf("Input x:");
        scanf("%d",&x);
        if(x>=0){
            printf("%d\n",x);
        }
        else
        {
          goto END;
        }
    }
    END: printf("Game is over.");
    return 0;
 } 

break:

#include<stdio.h>
int main()
{
    int index=0,x;
    while(index<5)
    {
        printf("Input x:");
        scanf("%d",&x);
        if(x>=0){
            printf("%d\n",x);
        }
        else
        {
          break;
        }
    }
    printf("Game is over.");
    return 0;
 } 

6.12 用continue替代上面的break,看看有什么变化。

(略)

6.13 韩信点兵 穷举法

(略)

猜你喜欢

转载自www.cnblogs.com/SlowIsFast/p/10434276.html
今日推荐