一覽2種類型互換方式「如何將int轉為string類型」

兩個C++編程中常見的小知識——int和string類型轉換、隨機數生成

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;

}

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/281420.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-21 13:18
下一篇 2024-12-21 13:18

相關推薦

發表回復

登錄後才能評論