zoukankan      html  css  js  c++  java
  • 关于随机数小游戏

    最开始写代码,没有考虑到保证随机种子的不同,导致随机数一直为41,经修改后加上#include<time.h>与srand(time(NULL));运行成功。
    引用:“在C语言中,rand()函数可以用来产生随机数,但是这不是真正意义上的随机数,是一个伪随机数,它是根据一个数,我们可以称它为种子,为基准以某个递推公式推算出来的一系数,但这不是真正的随机数,当计算机正常开机后,这个种子的值是定了的,除非你破坏了系统,为了改变这个种子的值。
    因此,C提供了srand()函数,它的原型是 void srand( int a)。用来改变这个种子值。
    srand( (time(NULL) )中time(NULL)函数是得到一个从1900年1月1日到现在的时间秒数,这样每一次运行程序的时间的不同就可以保证得到不同的随机数了。”
    代码如下:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    int main()
    {
    srand(time(NULL));
    int number=1+(rand()%100);
    int x=0;
    int y=20,a;
    printf("你有20次机会来猜这个数字
    ");
    for(;y>0;y--)
    {
    printf("请输入你猜测的号码:");
    scanf("%d",&x);
    if(number==x)
    {
    printf("恭喜你,你猜中了,");
    a=21-y;
    printf("次数为%d
    ",a);
    return 0;
    }
    {if(x>number) 
    printf("大了,你还剩余%d次机会!
    ",(y-1));
    if(x<number) 
    printf("小了,你还剩余%d次机会!
    ",(y-1));
    }
    }
    return 0;
    }
  • 相关阅读:
    173. Binary Search Tree Iterator
    199. Binary Tree Right Side View
    230. Kth Smallest Element in a BST
    236. Lowest Common Ancestor of a Binary Tree
    337. House Robber III
    449. Serialize and Deserialize BST
    508. Most Frequent Subtree Sum
    513. Find Bottom Left Tree Value
    129. Sum Root to Leaf Numbers
    652. Find Duplicate Subtrees
  • 原文地址:https://www.cnblogs.com/yang12318/p/7701318.html
Copyright © 2011-2022 走看看