生成随机数

<cstdlib>定义了int rand(),返回0到RAND_MAX之间的值

<ctime>定义了time_t time(time_t* time), time_t等价long

srand((unsigned int)time(0));为随机序列创建种子

1)随机数在0到10之间 

const int limit=11;
int random_value=static_cast<int>((limit*static_cast<long>(std::rand()))/(RAND_MAX+1L));


2)随机值在1到100之间

const int limit=100;
int random_value=static_cast<int>(1L+(limit*static_cast<long>(std::rand()))/(RAND_MAX+1L));

在1到49之间选择6个不同的整数

// Exercise 5.6 Generate a lottery entry consisting of 6 numbers from 1 to 49
#include <iostream>
#include <iomanip>
#include <cmath>
#include <ctime>
using std::cout;
using std::endl;
using std::setw;

int main() {
  const int selections = 6;                            // Number of selections in an entry
  const int n_max = 49;                                // Maximum value of a selection
  int n1 = 0, n2 = 0, n3 = 0, n4 = 0, n5 = 0, n6 = 0;  // Selections in an entry
  int possible = 0;                                    // Selection candidate

  std::srand(static_cast<unsigned int>(std::time(NULL)));

  for (int i = 1 ; i<= selections ; i++)
    while(true) {
      possible = static_cast<int>(std::ceil(static_cast<double>(n_max*std::rand())/RAND_MAX));
      possible = possible == 0 ? 1 : possible;  // Make sure it's at least 1
    switch(i) {
      case 1:
        n1 = possible;
        break;
      case 2:
        if(possible == n1)
          continue;
        n2 = possible;
        break;
      case 3:
        if(possible == n1 || possible == n2)
          continue;
        n3 = possible;
        break;
      case 4:
        if(possible == n1 || possible == n2 || possible == n3)
          continue;
        n4 = possible;
        break;
      case 5:
        if(possible == n1 || possible == n2 || possible == n3 || possible == n4)
          continue;
        n5 = possible;
        break;
      case 6:
        if(possible == n1 || possible == n2 || possible == n3 || possible == n4 || possible == n5)
          continue;
        n6 = possible;
        break;
    }
    break;
  }
    cout << "Your lottery entry for this week is :" << endl
         << setw(4) << n1 << setw(4) << n2 << setw(4) << n3 
         << setw(4) << n4 << setw(4) << n5 << setw(4) << n6 << endl;
  return 0;
}


 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值