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

Go EP.7 Go Unit Testing

สวัสดีครับ ในบทความนี้ก็เป็น EP.7 แล้วนะครับ โดยเนื้อหาจะเป็นเรื่องเกี่ยวกับ Unit Testing ซึ่งเป็นเรื่องที่มีความสําคัญในการพัฒนาโปรแกรมมากๆครับสําหรับท่านใดที่ยังไม่ได้อ่าน EP.6 ท่านสามารถกลับไปอ่านก่อนได้นะครับที่นี่ Go EP.6 Go Channelมาเริ่มเรียนรู้ไปด้วยกันตามหัวข้อด้านล่างเลยครับ

ทดสอบประสิทธิภาพของ web server ด้วย Apache Benchmark (Ab)

เมื่อเราพัฒนา web site หนึ่งขึ้นมา เราจะรู้ได้อย่างไรว่าเว็บเรามีความเร็วในการทํางานมากน้อยแค่ไหน หรือแม้กระทั่ง Server ของเราทํางานได้ดีแค่ไหน สามารถรองรับ user ได้เท่าไร โดยปกติเมื่อเราติดตั้ง Apache จะมี tool ตัวนึงชื่อว่า ab (Apache Benchmark) ติดมาด้วย ซึ่ง tool ตัวนี้สามารถจําลองการเรียกใช้งานเว็บตาม path ที่เราระบุ

Journaling file system คืออะไร

Journaling file system เป็น file system ที่เก็บการเปลี่ยนแปลงของข้อมูลที่ยังไม่ถูกบันทึกลง system หลัก ซึ่งจะช่วยทําให้ไม่เกิดการสูญหายของข้อมูล เมื่อเกิดปัญหากับ Hardware เช่น ไฟดับ หรือระบบส่วนใดส่วน


Copyright © 2019 - 2025 thiti.dev |  v1.58.0 |  Privacy policy | 

Build with ❤️ and Astro.

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