0

How does this code work?

(n + rand() % x) Where n & x are integer numbers I eant know, how does this function use n & x ??

26th Jul 2020, 5:57 PM
‎Mustafa Haider
‎Mustafa Haider - avatar
4 Réponses
+ 2
Rand() is a function in c++ that returns a random whole number(int) beetween 0 and RAND_MAX (for more information look at rand() reference in c++ documantation) n and x are variables, as you said of type int (0,1,2,3,565,1000, -20...) and they are declared in the user input or hardcoded into the program % - mod - it returns the leftover of division beetween two int numbers i.e. (25 % 6 = 1) % has higher priority than + operator Therefore , this program will return value of Case 1 : (n + random int) if x is higher than rand Case 2 : (only n) if x is equal to that random value or Case 3 : (n + leftover) if x is lower than random int
26th Jul 2020, 6:36 PM
Kristijan Fajdetic
Kristijan Fajdetic - avatar
+ 1
n and x are variables they have to be declared some where earlier in the program. https://code.sololearn.com/c0J9eryN6Fq8/?ref=app
26th Jul 2020, 6:32 PM
sneeze
sneeze - avatar
0
Kristijan Fajdetic I want to understan, why does the output be greater than x?? Isn't x value the range of rand?
28th Jul 2020, 6:17 PM
‎Mustafa Haider
‎Mustafa Haider - avatar
0
No rand() is a solo part if this equation. The equation says Number n plus a random number Then Take the result and get modulus using x N=1 Random number example 6 X=2 1+6 = 7 7%2 = 1 (read remainder of 7/2) N=3 Random number example 5 X=4 3+5 =8 8%4 = 0 (read remainder of 8/4) http://www.cplusplus.com/reference/cstdlib/rand/ ok. This article says that you can use the modulus (x) to define the range. But that is not a parameter of the rand- method. n is offset x is maximum number Have a look at my code I added some extra explanation.
28th Jul 2020, 7:35 PM
sneeze
sneeze - avatar