第四周项目3————随机数函数应用于游戏

本文介绍两个C++程序示例:一是随机生成数字让用户猜测,并提供反馈;二是为小学生设计的算术练习程序,随机生成四则运算题目并验证答案。
/*copyright(c)2016.烟台大学计算机学院
 * All rights reserved,
 * 文件名称:text.Cpp
 * 作者:吴敬超
 * 完成日期:2016年3月22日
 * 版本号:vc++6.0
 *
 * 问题描述: 随机产生一个1000以内的数字,要求用户猜测这个整数。输入一个猜想的整数,判断是否与产生的随机数相等,由屏幕显示
              判断的结果,如果猜的不对,给出“大了”或“小了”的提示,直到猜到这个数为止。(可以再加一个要求,猜了几次才得到正确结果)
 * 输入描述:  有电脑产生一个随机数
 * 程序输出: 输出结果
 */
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
    int n,x,i=1;
    n=rand()%1000+1;
    while(true)
    {
        cin>>x;
        if(n==x)
        {
            cout<<"right"<<endl;
            cout<<"猜了:"<<i<<"次"<<endl;
            break;
        }
        else if(n<x)
        {
            cout<<"大了"<<endl;
            i++;
        }
        else if(n>x)
        {
            cout<<"小了"<<endl;
        i++;
        }


运行结果:

(2)

/*copyright(c)2016.烟台大学计算机学院
 * All rights reserved,
 * 文件名称:text.Cpp
 * 作者:吴敬超
 * 完成日期:2016年3月22日
 * 版本号:vc++6.0
 *
 * 问题描述: 设计一个程序,用来实现帮助小学生进行算数练习
 * 输入描述:  有电脑产生数
 * 程序输出: 输出结果
 */
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
    int a,b,sum,n,c;
    while(true)
    {
        a=rand()%100+1;
        b=rand()%100+1;
        c=rand()%4+1;
        if(c==1)
        {
            sum=a+b;
            cout<<a<<"+"<<b<<"="<<endl;
            cin>>n;
            if(sum==n)
            {
                cout<<"right"<<endl;
            }
            else
            {
                cout<<"wrong"<<endl;
            }
        }
        if(c==2)
        {
            sum=a-b;
            cout<<a<<"-"<<b<<"=";
            cin>>n;
            if(sum==n)
            {
                cout<<"right"<<endl;
            }
            else
            {
                cout<<"wrong"<<endl;
            }
        }
        if(c==3)
        {
            sum=a*b;
            cout<<a<<"*"<<b<<"=";
            cin>>n;
            if(sum==n)
            {
                cout<<"right"<<endl;
            }
            else
            {
                cout<<"wrong"<<endl;
            }
        }
        if(c==4)
        {
            sum=a/b;
            cout<<a<<"/"<<b<<"=";
            cin>>n;
            if(sum==n)
            {
                cout<<"right"<<endl;
            }
            else
            {
                cout<<"wrong"<<endl;
            }
        }
    }
    return 0;
}

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值