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

Stateless Component ใน React

สวัสดีครับ บทความนี้จะเกี่ยวกับ การสร้างและใช้งาน Stateless Component ใน React ซึ่งเป็นการสร้าง Component อีกรูปแบบหนึ่ง ที่ภายใน Component จะไม่มี State

pointer c/c++

pointer เป็นชนิดข้อมูลประเภทหนึ่งที่สร้างจากชนิดข้อมูลแบบพื้นฐานทั่วไป โดยชนิดข้อมูลแบบ pointer จะแตกต่างกับชนิดข้อมูลพื้นฐานตรงที่ชนิดข้อมูลแบบพื้นฐานจะเก็บและดึงข้อมูลจากตัวแปรโดยตรง แต่ชนิดข้อมูลแบบ pointer จะเก็บค่าที่อยู่(Address) ของตัวแปรอื่น และใช้ค่าที่อยู่นี้อ้างอิงไปยังข้อมูลที่เก็บอยู่ในตัวแปรนั้นอีกที เพื่อทําการเก็บและดึงข้อมูลจากตัวแปรนั้นอีกที

รหัส ว. ที่ใช้กันทั่วไป

รหัส ว. ที่ใช้ในการติดต่อสื่อสารทั่วไปว. 00 คอยก่อนให้คอยอยู่ ว. 01 ที่ทำงาน ว. 02 ที่พัก ว. 0 ขอทราบคำสั่งคำสั่ง ว. 1 อยู่ไหนอยู่ที่


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

Build with ❤️ and Astro.

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