zoukankan      html  css  js  c++  java
  • 整数加减法练习

     程序自动产生随机数(srand 设置种子为系统时间,以保证每次运行程序产生的随机数有差别 ),然后用户输入结果,程序判断用户输入是否正确

     减法运算时要保证随机产生的a要大于b(用while循环判断,当然前提条件是用户选择的为减法运算,这里只保证式子产生的结果为非负整数)。

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main()
    {
      int a,b,c,sign,max;
      char sign1;
      printf("please select sign(1 or other,1:-,oteher:+):
    ");
      scanf("%d",&sign);
      printf("please select the max number(<10000):
    ");
      scanf("%d",&max);
      srand((unsigned long)time((time_t *)NULL));
      a=rand()%max;
      b=rand()%max;
      while((a<b)&&(sign==1))
          {
         a=rand()%max;
         b=rand()%max;
    
        }
       sign1=(sign==1?'-':'+');
       printf("
    %d%c%d=",a,sign1,b);
       scanf("%d",&c);
       if((sign==1)&&(a-b==c)||(sign!=1)&&(a+b==c))
           {
          printf("OK!
    ");
        }
       else
             printf("The result is wrong!
    ");
       
    
    }

    程序运行结果如下:

    最后附上本程序涉及到的函数原型 

     

    srand(设置随机数种子)
    相关函数
    rand,random srandom
    表头文件
    #include<stdlib.h>
    定义函数
    void srand (unsigned int seed);
    函数说明
    srand()用来设置rand()产生随机数时的随机数种子。参数seed必须是个整数,通常可以利用geypid()或time(0)的返回值来当做seed。如果每次seed都设相同值,rand()所产生的随机数值每次就会一样。

     

     

    rand(产生随机数)
    相关函数
    srand,random,srandom
    表头文件
    #include<stdlib.h>
    定义函数
    int rand(void)
    函数说明
    rand()会返回一随机数值,范围在0至RAND_MAX 间。在调用此函数产生随机数前,必须先利用srand()设好随机数种子,如果未设随机数种子,rand()在调用时会自动设随机数种子为1。关于随机数种子请参考srand()。
    返回值
    返回0至RAND_MAX之间的随机数值,RAND_MAX定义在stdlib.h,其值为2147483647。

     

    相关函数
    ctime,ftime,gettimeofday
    表头文件
    #include<time.h>
    定义函数
    time_t time(time_t *t);
    函数说明
    此函数会返回从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数。如果t 并非空指针的话,此函数也会将返回值存到t指针所指的内存。
    返回值
    成功则返回秒数,失败则返回((time_t)-1)值,错误原因存于errno中。
       
  • 相关阅读:
    Android 获取自带浏览器上网记录
    android 中的 ViewPager+ Fragment
    Git分支操作
    图形验证码的识别
    mac平台搭建安卓开发环境
    [报错集合]Uncaught ReferenceError: xxx is not defined
    Centos安装Python3
    VSCode 代码格式化 快捷键
    Mac下用Parallels Desktop安装Ubuntu
    请求头headers
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/3703040.html
Copyright © 2011-2022 走看看