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

โครงสร้างของ jpg file (jpg structure format)

โครงสร้างของ jpg fileเรารู้จักกันดีนะครับว่า jpg file เป็นไฟล์รูปภาพ ในบทความนี้เราจะมาดูกันว่าโครงสร้างของไฟล์รูปภาพ หรือ jpg file เป็นอย่างไร เมื่อเราใช้โปรแกรมพวก Hex Viewer ต่างๆ เปิด jpg file ดู เราจะสามารถดูเนื้อของไฟล์ที่ถูกเขียนบน hdd ได้ซึ่งจะแสดงผลเป็นเลขฐาน 16

Install docker on raspberry pi

ในบทความนี้ผมจะพูดถึงวิธีการ install docker ใน raspberry pi (สําหรับใครที่ยังไม่รู้ว่า Docker คืออะไรให้อ่านบทความนี้ก่อน Docker คืออะไร ครับ) เริ่มต้นด้วยการเตรียมอุกปรณ์ดังนี้raspberry pi (ในบทความนี้ผมใช้ raspberry pi 2)SD Card ที่ติดตั้ง RASPBIAN เรียบร้อยวิธีติดตั้งสามารถทําได้สองวิธีคือ

วิธีใช้ คําสั่ง top ดู process ของโปรแกรม ที่ต้องการ

วิธีใช้ คําสั่ง top ดู process ของโปรแกรม ที่ต้องการ ใช้คําสั่งดังนี้


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

Build with ❤️ and Astro.

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