|
Post by Admin on Sept 27, 2016 2:57:10 GMT
This should make it obvious to everyone that I am not even level 0 as a programmer!
Intent: randomly generate a race, print to screen.
v1 = rand() % 100 + 1;
if v1 = 1 then r = human; if v1 = 2 then r = dwarf; if v1 = 3 then r = elf; if v1 = 4 then r = gnome; if v1 = 5 then r = half-elf; if v1 = 6 then r = half-orc if v1 = 7 then r = hobbit;
cout(v1);
|
|
Lee
Basic Member
Posts: 43
|
Post by Lee on Sept 27, 2016 21:50:18 GMT
Thoughts:
On some systems, modulus random number generation won't give you a quite right probability spread, because computers think in base 2 instead of base 10. Google for "modulo bias". This may be too nitpicky, so it may not be worth considering. What you are doing will work fine most of the time unless you are trying to do crypto or something.
You're generating a number between 1-100, and only testing the first 7 values. The if block will fall off the end without setting <r> to anything. In a case like this, you can write more robust code using a switch-case statement:
srand( timer() ); // Don't forget to seed your random number generator at the beginning of your code. Odd C gotcha there. switch( rand()%100 + 1 ) { case 1: r=HUMAN; break; case 2: r=DWARF; break; case 3: r=ELF; break; case 4: r=GNOME; break; case 5: r=HALFELF; break; case 6: r=HALFORC; break; case 7: r=HOBBIT; break; default: printf( "Fell through switch statement. This should never happen, so there must be an error in the code.\n" ); exit(1); }
In the above code, it will check through those 7 values, but if you have generated a random number that isn't handled by the code, it will be caught by the "default" statement, print an error, and exit. Instead of going on to do weird stuff elsewhere in the code where nothing is actually wrong, but since <r> hasn't been set.
|
|
Lee
Basic Member
Posts: 43
|
Post by Lee on Sept 27, 2016 21:53:35 GMT
PS, if you are looking to write a game, you may be better off using a more specialized game development toolkit, instead of a general purpose programming language. "Unity" may be a good choice. It has a good editor, scripting in C#, and is free for noncommercial work.
|
|
|
Post by Alex on Sept 16, 2019 20:05:26 GMT
Our aim is to examine the way blockchain technologies can bring about and justify new models of governance. Learn more about it on blockchain cloud .
|
|