+ 1

How do i assign a random number to a int or a var?

I was trying to assign random numbers to an int and it refused to work idk if Iā€™m messing up the = and the == but Iā€™m a doing something wrong. It works when I cout the random number but it doesnā€™t save when I assign it to a value

18th Jan 2018, 1:38 PM
Lord Awesome
Lord Awesome - avatar
6 Answers
+ 2
Since you use cout, I assume your question is for C++. It works just like every other assignment: int var = rand(); , where var will be a random value between 0 and, by default, 32767 I think. You can limit the range using int var = x + rand() % y; , where x is the lowest possible number and y the upper limit (not included in range though). Then you can use var in your code, just make sure you included <cstdlib> for the rand()-prototype and <ctime> if you seed with a time value.
18th Jan 2018, 1:52 PM
Shadow
Shadow - avatar
+ 1
Thats because 1) you use a wrong operator. One = is enough when assigning values. 2) In an assignment, there are lvalues (left side of =) and rvalues (right side of =). The value you are trying to assign has to be the rvalue! In conclusion, lines 20 - 26 should look like a = rand();
19th Jan 2018, 5:54 AM
Shadow
Shadow - avatar
0
lol sorry i forgot to tag that
19th Jan 2018, 3:20 AM
Lord Awesome
Lord Awesome - avatar
0
thanks
19th Jan 2018, 3:20 AM
Lord Awesome
Lord Awesome - avatar
0
with that my code still outputs the same info tho it dosent change https://code.sololearn.com/ciJARBLbpP7V/?ref=app
19th Jan 2018, 3:21 AM
Lord Awesome
Lord Awesome - avatar
0
Thanks I thought it was like math were you can switch sides I had no idea this affected the way you code
19th Jan 2018, 1:27 PM
Lord Awesome
Lord Awesome - avatar