+ 2

how to make random statement

I want to make program like sometimes it alert good morning and sometimes good night. Can it happen

15th Oct 2016, 6:02 AM
abhijeet chatterjee
abhijeet chatterjee - avatar
4 Antworten
+ 4
I am new to Javascript a bit, I'm used to C++ so sorry if messed up. What you can do, is make a if statement where it asks for the AM or PM Idk how to get user input for Javascript, but this is the way it would be with C++ if it helps you I made it so it's easy to copy and paste, but it's untested Paste this after the first function (after int Main() and in the brackets) int answer1 cout >> "Please enter AM or PM" cin << answer1; if (answer1==am){"It is am" } if (answer1==pm){"It is pm" } else() {"This is a unvalid" }
15th Oct 2016, 7:31 PM
Dillion Piazza
Dillion  Piazza - avatar
+ 1
Hi. You need to learn more about the "Math.random()" function. Try this sample code: function getRandomGreeting() { if (Math.random()>0.5) { return "Good Morning!"; } else { return "Good Night!"; } } alert(getRandomGreeting()); You can find more info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
15th Oct 2016, 7:35 PM
yugor
+ 1
Thanks I found it helpful but want to ask why you take 0.5
16th Oct 2016, 3:38 AM
abhijeet chatterjee
abhijeet chatterjee - avatar
+ 1
>>why you take 0.5 It is because of "Math.random()" returns values between 0 and 1 (1 is not including, so the range will be [0-0,99999(9)]. I took 0,5 as a half to get two different states. Half of the results will be below 0,5 and other half - above 0,5. Actually, you can multiply the result of Math.random() to any needed number, round the value and then use switch statement.
16th Oct 2016, 5:55 AM
yugor