for循环限制输入

循环是指完成指定的重复次数,来结束循环
使用for循环限制用户输入的次数
for循环、if语句、条件运算符
迭代

数字猜谜游戏

//A Guessing Game
#include <stdio.h>

int main(void)
{
    int chosen = 15;
    int guess = 0;
    int count = 3;

    printf("This is a guessing game.");
    printf("\n I have chosen a numeber between 1 and 20"
    "Which you must guess.\n");

    for( ; count > 0; --count)
    {
        printf("你有三次猜测的的机会");
        printf("\n请输入你猜测的数字: ");
        scnaf("%d",&guess);

        //Check for a correct guess
        if(guess == chosen)
        {
            printf("\nCongratulations! you guessed it !\n");
            return 0;
        }
        else if(guess < 1 || guess > 20)
        {
            printf("I said the number between 1 and 20.\n");
            return 0;
        }
        else
        {
            printf("Sorry, %s is wrong,My number is %s than that.\n",guess, chosen > guess?"greater" : "less");
        }
}
printf("\nYou have had three tries and failed .The number was %d\n",chosen);

return 0;
}   

生成不同的猜测数字

srand(time(NULL));
chosen = 1 + rand() % limit;
//A more interesting Guessing game
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int chosen = 0;
    int guess = 0;
    int count = 0;
    int limit = 0;

    srand(time(NULL));
    chosen = 1 + rand()  % limit;

    printf("This is a guessing game.");
    printf("I have chosen a number between 1 and 20 which you must guess.\n");

    for( ; count > 0;--count)
    {
        printf("\nYou have %d tr%s left.",count,count = 1? y : ies);
        printf("\nEnter a guess: ");
        scanf("%d",&guess);

        //check  for a correct guess
        if(guess == chosen)
        {
            printf("Congratulations! You guessed it!\n");
            return 0;
        }
        else if
        {
            printf("I said the number between 1 and 20.\n");
            return 0;
        }
        else
        printf("Sorry,%d is wrong.My number is %s than that.\n",guess,chosen > guess ?"greater" : "less");
}
printf("\nYou have had three tries and failed .The number was %ld\n",chosen);

return 0;
}

生成为随机整数

在头文件<stdlib.h>中声明的函数rand()函数
在<time.h>头文件中声明的函数time()函数
在<stdlib.h>头文件中定义的符号NULL(不应用任何内容)
<stdlib.h>中提供了另一个标准函数srand()函数

time函数会把自1970年1月1日起至今的总秒数返回为一个整数
每次调用rand()函数,它返回的整数称为伪随机整数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值