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

พื้นฐานการเขียน JavaScript ES2015 (ES6)

ความเป็นมาของ JavaScriptเมื่อนานมาแล้ว JavaScript เป็นภาษา script ฝั่ง client ของ Netscape ซึ่งเป็น web browser ชื่อดังในสมัยนั้นครับ แล้วหลังจากนั้นไม่นาน Netscape ก็ได้นำเจ้า JavaScript นี้ไปฝากไว้กับ Ecma International ซึ่งเป็นองค์กรที่ก่อตั้งขึ้นเพื่อทำหน้าที่กำหนด standard ให้กับสิ่งต่างๆ โดยเฉพาะ เพื่อจะให้เข้ามาช่วยกำหนด standard ให้กับ JavaScript หลังจากนั้น JavaScript ก็ได้พัฒนาขึ้นมาเรื่อยๆ จนถึง JavaScript ES6

Conditional types ใน TypeScript

สวัสดีครับ ในบทความนี้เราจะมาเรียนรู้เรื่อง Conditional types ใน TypeScript ว่าคืออะไร นำไปใช้ประโยชน์ได้อย่างไร

ใช้ docker-compose ใน crontab

โดยปกติแล้วเราจะไม่สามารถเรียกใช้งาน docker-compose ได้ตรงๆใน crontab แต่ถ้าต้องการใช้ ให้ใช้วิธีนี้ครับ


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   วงแหวนเว็บ