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

Touchscreen calibration raspberry pi

วิธี calibration จอ touchscreen raspberry piในบทความนี้ จะอธิบายเกี่ยวกับการ calibration จอ touchscreen ของ raspberry pi โดยจอ touchscreen ที่ใช้คือ Raspberry Pi 7" Touchscreen Display มาเริ่มกันเลยครับ

Review ไฟฉาย JetBeam IIM

ไฟฉาย JetBeam รุ่น IIM เป็นไฟฉายรุ่นที่มีความสว่างสูงสุด 1,100 Lumens แสงพุ่งไกลถึง 230 เมตร จุดเด่นคือ สามารถล็อค switch ปิด-เปิด ได้เพื่อป้องกันไม่ให้เปิดไฟฉายโดยบังเอิญ

TTL UART RS232 คืออะไร

สําหรับผู้ที่เริ่มต้นศึกษา Microcontroller จะต้องรู้จักและเข้าใจในเรื่องของการสื่อสารแบบ Serial เนื่องจากเป็นรูปแบบการสื่อสารที่นิยมใช้เพื่อสื่อสารกันระหว่าง Microcontroller กับคอมพอวเตอร์, RFID, RTC, GSM ฯลฯการสื่อสารแบบ Serail มีด้วยกันหลายรูปแบบเช่น TTL, UART, RS232 ในแต่ละแบบ ก็มีวิธีการใช้งาน และการทํางานที่แตกต่างกันไปดังนี้


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

Build with ❤️ and Astro.

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