设为首页收藏本站

Crossin的编程教室

 找回密码
 立即加入
查看: 96163|回复: 2
打印 上一主题 下一主题

【每日一坑 1】 随机取数

  [复制链接]

0

主题

0

好友

79

积分

注册会员

Rank: 2

楼主
发表于 2013-12-13 01:09:30 |显示全部楼层

回帖奖励 +5

本帖最后由 xuefu 于 2013-12-13 01:21 编辑
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>

  5. int main(int argc, const char *argv[])
  6. {
  7.   int a, n, m, i = 0, j = 0;
  8.   int* secret;

  9.   printf("Input n: ");
  10.   scanf("%d", &n);

  11.   assert(n > 1 || n == 1);

  12.   printf("Input m: ");
  13.   scanf("%d", &m);

  14.   if(m > 0 && !(m > n))
  15.     printf("Below is the number: \n");
  16.   else
  17.   {
  18.     printf("the number m should be greater than zero and not larger than n.\n");
  19.     exit(0);
  20.   }

  21.   secret = malloc(sizeof(int) * m);
  22.   srand(time(NULL));

  23.   while(m--)
  24.   {
  25.     /* generate the number you want */
  26.     while(1)
  27.     {
  28.       a = rand() % n + 1;
  29.       /* check a whether is repeated */
  30.       for (j = 0; j < i; j++)
  31.       {
  32.         if (a == secret[j])
  33.         {
  34.           a = 0;
  35.           break;
  36.         }
  37.       }
  38.       if(a != 0)
  39.         break;
  40.     }
  41.     secret[i] = a;
  42.     printf("%d  ", secret[i++]);
  43.   }
  44.   printf("\n");

  45.   free(secret);
  46.   return 0;
  47. }
复制代码
回复

使用道具 举报

0

主题

0

好友

79

积分

注册会员

Rank: 2

沙发
发表于 2013-12-13 01:11:25 |显示全部楼层
judy 发表于 2013-12-12 23:27
import random
def tool():
    m=input("需要几个数:")

明显得到的数可能会重复。。。
回复

使用道具 举报

0

主题

0

好友

79

积分

注册会员

Rank: 2

板凳
发表于 2013-12-13 11:47:04 |显示全部楼层
byron 发表于 2013-12-13 08:55
你这是C啊?

楼主没说一定要用Python啊。。。吱吱,还不会Python
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即加入

QQ|手机版|Archiver|Crossin的编程教室 ( 苏ICP备15063769号  

GMT+8, 2024-5-3 08:40 , Processed in 0.016390 second(s), 22 queries .

Powered by Discuz! X2.5

© 2001-2012 Comsenz Inc.

回顶部