0

Why my code generating the same matrix all the time

#include <iostream> using namespace std; int main(void) { const int S = 9; int matrix[S][S]; // filling matrix with random numbers between 0 and 99 for (int i = 0; i < S; i++) { for (int k = 0; k < S; k++) { matrix[i][k] = rand() % 100; } } // print matrix for (int i = 0; i < S; i++) { for (int k = 0; k < S; k++) { printf("%3d", matrix[i][k]); } printf("\n"); } }

9th Dec 2019, 8:15 AM
bdjdndnd hdhdbd
bdjdndnd hdhdbd - avatar
2 Respuestas
+ 4
hello bdjdndnd hdhdbd , rand() function by itself can't generate random numbers. """ You'll need to use 2 libraries to generate random numbers. 1. ctime 2. cstdlib Use srand and rand functions srand seeds value for pseudo-random generator rand returns random value based on seeded value. using rand without any call to srand will give results as if srand was seeded by 1. It'll not give you really random nos so pass time(0) as arg to srand as srand(time(0)); Now rand is ready to use but every time it'll return value b/w 0 and MAX_RAND so trick is using %. Using rand()%n will give random no b/w 0 to n. To get no.s b/w 1 to 100 use 1+rand()%100; Why % works? Well, modulus division by n makes sure that result will be less than n.//got it? """ quote of my own answer(little customized) : https://www.sololearn.com/discuss/2030471/?ref=app
9th Dec 2019, 8:31 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
you are right, thanks a lot
9th Dec 2019, 8:33 AM
bdjdndnd hdhdbd
bdjdndnd hdhdbd - avatar