random ใน ภาษา c, c++

16 Nov 2015,
Share: 

การเขียนโปรแกรมสุ่มเลข หรือrandom ในภาษา c, c++ จะใช้ 2 function หลักๆคือ

  • void srand(unsigned int seed); <---ใช้กำหนดค่า seed ให้กับ function rand();
  • int rand (void); <---ใช้ random

srand();

คือ function ที่ใช้กําหนดค่า seed ให้กับ function rand(); เพื่อให้ ทุกครั้งที่รันโปรแกรม ผลการ random จะออกมาไม่ซํ้ากัน โดยปกติจะเขียนแบบนี้ครับ

srand(time(NULL));

rand();

คือ function ใช้สําหรับ random ตัวเลข 0-32767 โดยมากจะใช้ %(mod) เข้ามาช่วย คือ ถ้าต้องการ random เลข 0-9 จะเขียน code ได้ดังนี้

int randomNumber = rand()%10;

หรือ ถ้าต้องการ random เลข 50-200 จะเขียน code แบบนี้

int randomNumber = 50+(rand()%(200-50));

ตัวอย่างการเขียน random ในภาษา c, c++

#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#include "time.h"


int main(){
	srand(time(NULL));

	int randomNumber1 = rand() % 10; //0-10
	int randomNumber2 = rand() % 10; //0-10
	int randomNumber3 = 50+(rand()%(10-50)); //50-200

	printf("Random number1 is %d\n", randomNumber1);
	printf("Random number2 is %d\n", randomNumber2);
	printf("Random number3 is %d\n", randomNumber3);
	getch();
}

Suggestion blogs

การเข้ารหัสข้อมูลแบบอสมมาตร (Asymmetric key)

อัลกอริทึมนี้จะใช้กุญแจสองตัวเพื่อทำงาน ตัวหนึ่งใช้ในการเข้ารหัสและอีกตัวหนึ่งใช้ในการถอดรหัสข้อมูลที่เข้ารหัสมา โดยกุญแจตัวแรก คือ กุญแจสาธารณะ (Public keys) ซึ่งจะเป็นกุญแจที่ใช้ในการเข้ารหัสข้อมูล กุญแจตัวที่สองคือ กุญแจส่วนตัว (Private keys) ซึ่งจะเป็นกุญแจที่ใช้ในการถอดรหัส อ่านๆไปแล้วอาจจะงงว่าจะเอาไปใช้ได้อย่างไร เรามาดูการทํางานกันดีกว่า

Arduino ตอน7 ใช้ DS18B20 (Digital Temperature Sensor) กับ Arduino

สวัสดีครับ ในบทความนี้จะมีเนื้อหาเกี่ยวกับวิธีการใช้งาน DS18B20 (Digital Temperature Sensor) กับ Arduino กันนะครับ เพื่อเรียนรู้การใช้งาน Arduino กับ Digital Temperature Sensor ผ่าน 1-Wire Protocol

Load test website ด้วย wrk

สวัสดีครับ ในบทความนี้เรามาเรียนรู้วิธีการทํา Load test กับ website ของเรากันนะครับ ก่อนอื่นเรามาดูก่อนครับว่าการทํา load test กับเว็บของเราคืออะไร ทําไปไทําไมครับ


Copyright © 2019 - 2026 thiti.dev |  v1.61.0 |  Privacy policy | 

Build with ❤️ and Astro.

Github profile   Linkedin profile   Instagram   X profile   Nostr   Youtube channel   Telegram   Email contact   วงแหวนเว็บ