行业新闻
如何将int转为string类型(一览2种类型互换方式)
2022-02-25 19:59  浏览:0

1、int、string类型互相转换

int->string:std::to_string(int val),同样适用于double, float等类型

string->int:atoi(const char*) 或stoi(const string*) (stoi增加了范围检查功能,无需像atoi一样使用str.c_str进行转换)

2、随机函数的生成

void srand(unsigned int seed):用来产生随机数的种子,一般seed是个整数,通常用time(0)或time(NULL)作种子(因为NULL的值一般为0),返回值代表从1970.1.1起至今所经历的秒数,如果seed每次都设相同的值,rand()(见下面)产生的随机数就会一样。

int rand(void):产生伪随机数,用户为设定随机数种子时,系统默认为1。

例子:

// 产生100个[MIN, MAX]范围内的随机数

#include<iostream>

#include<stdlib.h>

#include<time.h>

#define MIN=0

#define MAX=99

int main{

srand(unsigned time(0));

for (int i = 0; i < 100; i++)

std::cout << MIN + rand() % (MAX-MIN +1) << std::endl;

}