Is there a shorthand notation for this operation? - c

Is there no shorthand notation like /= for this operation in C?
int variable = 5;
variable = round(variable / (float)2);
I can't think of any.

So it really depends what you're doing. Most of the time you shouldn't be actually concerned about shortcuts but readability and correctness. In this case your code is quite readable but it is not very correct, because it code divides by a float so the result has only23-24 bits of precision, less than in an int; even if you use a double 2.0, you get that 53-54 bits of precision which is less than long long int.
The codes below are likely not only faster but also work correctly in more cases.
If you want to work with unsigned numbers (or signed with non-negative values), then you can do this:
unsigned int variable = 5;
variable = (variable + 1) >> 1;
i.e. add 1 and bitshift right.
If you need to support signed and are using C99+ or C89 with properly-defined division (truncating towards zero), you can do
variable = (variable + (variable > 0 ? 1: -1)) / 2;
These work because integer division always return an integer:
#include <stdio.h>
int main(void) {
for (int i = -5; i <= 5; i ++) {
int variable = i;
variable = (variable + (variable > 0 ? 1: -1)) / 2;
printf("%3d\t%4.1f\t%3d\n", i, i/2.0, variable);
}
}
will print out:
-5 -2.5 -3
-4 -2.0 -2
-3 -1.5 -2
-2 -1.0 -1
-1 -0.5 -1
0 0.0 0
1 0.5 1
2 1.0 1
3 1.5 2
4 2.0 2
5 2.5 3

Related

How to handle "((9^x)-2)%5" without overflow at higher x?

I'm doing some exam prep for my discrete mathematics course, and I have to implement the function
f(x) = ((9^x)-2)%5
Since the values of our x in the assignment is 100000 < x <= 1000000, I'm having some trouble handling the overflow
In our assignment there's a hint: "Find a way to apply the modulus throughout the calculations. Otherwise you will get much too big numbers very quickly when calculating 9^x"
I cannot figure out the logic to make this work tho, any help would be appreciated
/* This function should return 1 if 9^x-2 mod 5 = 2 and 0 otherwise */
int is2mod5(int x){
int a;
double b = pow(9, x);
a = b;
int c = (a-2)%5;
if (c == 2)
{
return 1;
}
else
{
return 0;
}
}
Since you are calculating modulo 5, multiplications can be done modulo 5 as well. 9 is congruent to -1 modulo 5. Thus 9^x is congruent to (-1)^x modulo 5, i.e. 1 if x is even and -1 if x is odd. Subtracting 2 gives -1 and -3 which are congruent to 4 and 2 respectively.
Thus, f(x) is 4 if x is even and 2 if x is odd.

Our Exercise code is outputting an unexpected -1 and we don't know why

So we are working on an exercise for Uni and we can't figure out why this code outputs the second value as -1
We believe that it is due to the 16-bit limit but don't understand exactly why and can't find any sources on this issue since we don't know what it actually is. I'm sorry if this seems really stupid, please help D:
#include <stdio.h>
#include <stdint.h>
int main() {
int16_t y = 1024, z = 65; // auch "short" als Datentyp verwendbar
y = y * z;
printf("1. Ausgabe: %d\n", y);
printf("2. Ausgabe: %d\n", y / 3 * 3 - 3 * y / 3);
printf("\n");
return 0;
}
we expected the result to be 0 for 2. Ausgabe but it outputs -1
the range for a int16_t is −32,768 ... 32,767
y * z = 1024*65 = 66560 but hence will be stored as 66560 % 2^16 = 1024
so you still have y = 1024 and your statement y = y * z is useless
y / 3 * 3 = (y / 3) * 3 = 341 * 3 = 1023 != y because of rounding
3 * y / 3 = (3 * y) / 3 = y because there is no rounding
when you substract you get -1
the problem is you're overflowing your variable and doing integer divisions
use floats instead of int16_t
int16_t has the range [−32768, +32767] - you are overflowing that range immediately with the first multiplication.
What does the first printf print out? That should have been an indication. You also mention it in your question.
Google int16_t range and it will show you the range above. Try using an int32_t and see what difference that makes.
Given y = y * z; where all operands are type int16_t and the values are 1024 * 65 = 66560,
then there are two possibilities:
If your system is 8 or 16 bit, you will have 16 bit int type. There will be no type promotion of the operands since they are already 16 bits and you get a signed integer overflow, invoking undefined behavior. Since 16 bit signed integers can only store values up to 32767.
If your system is 32 bit, then both y and z are implicitly promoted (see Implicit type promotion rules) to type int which is then 32 bits. The result of the multiplication is of type int. The value 66560 will fit just fine.
You then convert this 32 bit int to int16_t upon assignment. The value will no longer fit - what will happen is an implementation-defined conversion from signed 32 to signed 16. (In theory your system may raise a signal here.)
In practice most systems will simply take the 66560 = 10400h and cut off the MS bytes, leaving you with 1024 = 400h.
In either case, the equation y = y * z; is highly questionable given the size of the input values! This is to be regarded as a bug. You should use uint16_t or int32_t instead.
As for y / 3 * 3 - 3 * y / 3, it will be 1024 / 3 * 3 - 3 * 1024 / 3. All operands are integers and the operator associativity of multiplicative operators * and / is left-to-right.
So you get 341 * 3 - 3072 / 3 -> 1023 - 1024 = -1.
As a side-note, you are using the wrong printf conversion specifier. The most correct one for int16_t is this:
#include <inttypes.h>
printf("1. Ausgabe: %"PRIi16 "\n", y);

C - Bit operation without loop

I am trying to calculate a value in function of bits in a word of variable length. Starting MSB, if bit is 1 then the value is 1/2^i. This value is multiplied by a scaling factor
Example: 110010
this would be (1/2 + 1/4 + 1/64) * scaling_factor
I have programmed it with a for loop; any idea of how this could be done avoiding the loop?
This is the code:
double dec_bnr (unsigned long data, int significant_bits, double scaling_factor)
{
unsigned int temp;
unsigned int bnr_locmask = 0x8000000;
temp = data & bnr_locmasks[significant_bits-1];
double result = 0;
for (int i=0; i<significant_bits; i++){
if((temp & bnr_locmask)==bnr_locmask){
result+=pow (0.5, i+1);
}
bnr_locmask = bnr_locmask >> 1;
}
return result * scaling_factor;
}
Thank you in advance!
Edit: Thank you for your answers; however, what I am trying to say is not what you propose. Please, let me add an example:
data=a0280
A 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192
1/A 0,5 0,125 0,000488281 0,00012207
data 1 0 1 0 0 0 0 0 0 0 1 0 1 0000000
result = scaling_factor*Sum(data/A)
We only take into account the value 1/A if the bit for that position is 1.
It's actually very easy to do without a loop:
double dec_bnr (unsigned long data, double scaling_factor)
{
return data*scaling_factor/(ULONG_MAX+1.0);
}
It's worth noting what happens in this code. First, data is converted into a double to match scaling_factor and then the numbers are multiplied, but then we do a further scaling dividing by ULONG_MAX+1.0 which is also converted to a double before dividing.
Note that
This can't be ULONG_MAX + 1 because that would cause the number to remain an integer type and wrap around to zero (and thus causing a divide-by-zero error at runtime).
The number ULONG_MAX + 1.0, interpreted as a double, may well be identical to ULONG_MAX on 64-bit machines
It's called fixed point arithmetic and there are many resources available on the internet and elsewhere that explain it very well.
Or you could use ldexp():
double result = ldexp(data * scaling_factor, -significant_bits) ;
which has the advantage of expressing exactly what you are doing ! (Assuming that the scaling_factor is double.)
It also avoids any issues with constructing large powers of two ((double)(ULONG_MAX + 1) doesn't quite work !) and dividing, or doing pow(2.0, -significant_bits) and multiplying.
Further thought... this is, of course, equivalent:
double result = ldexp((double)data, -significant_bits) * scaling_factor ;
But you could lump the "binary point shift" in with the scaling_factor (once):
double scaling_factor_x = ldexp(scaling_factor, -significant_bits) ;
and then the conversion is simply:
double result = (double)data * scaling_factor_x ;
This, or something similar, should be equivalent to what you are doing:
(double)data / 0x100000000 * scaling_factor
The way binary works is that each bit has a weight twice the weight of the bit after it, so you don't need to loop through the bits like you are doing.

What's the difference between “mod” and “remainder”?

My friend said that there are differences between "mod" and "remainder".
If so, what are those differences in C and C++? Does '%' mean either "mod" or "rem" in C?
There is a difference between modulus (Euclidean division) and remainder (C's % operator). For example:
-21 mod 4 is 3 because -21 + 4 x 6 is 3.
But -21 divided by 4 with truncation towards 0 (as C's / operator)
gives -5 with a remainder (C -21 % 4) of -1.
For positive values, there is no difference between Euclidean and truncating division.
See https://en.wikipedia.org/wiki/Euclidean_division#Other_intervals_for_the_remainder - C's choice of truncating the remainder towards 0 (required since C99) forces a negative remainder range for negative quotients. Even in C89, when Euclidean division was allowed by the standard for /
If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
(-21/4) * 4 + (-21%4) == -21; C99 and later require (-5) * 4 + (-1), not Euclidean -6 and 3.
Does '%' mean either "mod" or "rem" in C?
In C, % is the remainder1.
..., the result of the / operator is the algebraic quotient with any fractional part discarded ... (This is often called "truncation toward zero".) C11dr §6.5.5 6
The operands of the % operator shall have integer type. C11dr §6.5.5 2
The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder ... C11dr §6.5.5 5
What's the difference between “mod” and “remainder”?
C does not define a "mod" nor "modulo" operator/function, such as the integer modulus function used in Euclidean division or other modulo.
C defines remainder.
Let us compare "remainder" per the % operator to the Euclidean "mod".
"Euclidean mod" differs from C's a%b operation when a is negative.
// a % b, the remainder after an integer division that truncates toward 0.
7 % 3 --> 1
7 % -3 --> 1
-7 % 3 --> -1
-7 % -3 --> -1
"Mod" or modulo as in Euclidean division. The result is always 0 or positive.
7 modulo 3 --> 1
7 modulo -3 --> 1
-7 modulo 3 --> 2
-7 modulo -3 --> 2
Candidate modulo code:
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
Note about floating point: double fmod(double x, double y), even though called "fmod", it is not the same as Euclidean division "mod", but similar to C integer remainder:
The fmod functions compute the floating-point remainder of x/y. C11dr §7.12.10.1 2
fmod( 7, 3) --> 1.0
fmod( 7, -3) --> 1.0
fmod(-7, 3) --> -1.0
fmod(-7, -3) --> -1.0
Disambiguation: C also has a similar named function double modf(double value, double *iptr) which breaks the argument value into integral and fractional parts, each of which has the same type and sign as the argument. This has little to do with the "mod" discussion here except name similarity.
[Edit Dec 2020]
For those who want proper functionality in all cases, an improved modulo_Euclidean() that 1) detects mod(x,0) and 2) a good and no UB result with modulo_Euclidean2(INT_MIN, -1). Inspired by 4 different implementations of modulo with fully defined behavior.
int modulo_Euclidean2(int a, int b) {
if (b == 0) TBD_Code(); // perhaps return -1 to indicate failure?
if (b == -1) return 0; // This test needed to prevent UB of `INT_MIN % -1`.
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
1 Prior to C99, C's definition of % was still the remainder from division, yet then / allowed negative quotients to round down rather than "truncation toward zero". See Why do you get different values for integer division in C89?. Thus with some pre-C99 compilation, % code can act just like the Euclidean division "mod". The above modulo_Euclidean() will work with this alternate old-school remainder too.
sign of remainder will be same as the divisible and the sign of modulus will be same as divisor.
Remainder is simply the remaining part after the arithmetic division between two integer number whereas Modulus is the sum of remainder and divisor when they are oppositely signed and remaining part after the arithmetic division when remainder and divisor both are of same sign.
Example of Remainder:
10 % 3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]
-10 % 3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]
10 % -3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]
-10 % -3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]
Example of Modulus:
5 % 3 = 2 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is also positively signed. As both remainder and divisor are of same sign the result will be same as remainder]
-5 % 3 = 1 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is positively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor -2 + 3 = 1]
5 % -3 = -1 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is negatively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor 2 + -3 = -1]
-5 % -3 = -2 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is also negatively signed. As both remainder and divisor are of same sign the result will be same as remainder]
I hope this will clearly distinguish between remainder and modulus.
In C and C++ and many languages, % is the remainder NOT the modulus operator.
For example in the operation -21 / 4 the integer part is -5 and the decimal part is -.25. The remainder is the fractional part times the divisor, so our remainder is -1. JavaScript uses the remainder operator and confirms this
console.log(-21 % 4 == -1);
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
% is a remainder(leftover after dividend / divisor) NOT modulus.
You could write your own modulus function using the remainder(%) by the relation
((n%m)+m)%m
where `n` is the given number and `m` is the modulus
Find below the difference between the remainder and modulus values for the range n = (-7,7) and m = 3
n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
-------------------------------------------------------------------------
%(-m) -1 0 -2 -1 0 -2 -1 0 1 2 0 1 2 0 1 => remainder
% m -1 0 -2 -1 0 -2 -1 0 1 2 0 1 2 0 1 => remainder
mod m 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 => ((n%m)+m)%m
mod(-m) -1 0 -2 -1 0 -2 -1 0 -2 -1 0 -2 -1 0 -2 => ((n%m)+m)%m
Tips to remember:
n%(-m) = +(remainder)
(-n)%(m) = -(remainder)
sign of 'm' doesn't matter
n mod (-m) = -(result)
(-n) mod m = +(result)
sign of 'n' doesn't matter
For +ve 'n' and '%(-m)' or '%m' or 'mod m' gives the same remainder
In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.
7 modulo 3 --> 1
7 modulo -3 --> -2
-7 modulo 3 --> 2
-7 modulo -3 --> -1

How do I get a specific range of numbers from rand()?

srand(time(null));
printf("%d", rand());
Gives a high-range random number (0-32000ish), but I only need about 0-63 or 0-127, though I'm not sure how to go about it. Any help?
rand() % (max_number + 1 - minimum_number) + minimum_number
So, for 0-65:
rand() % (65 + 1 - 0) + 0
(obviously you can leave the 0 off, but it's there for completeness).
Note that this will bias the randomness slightly, but probably not anything to be concerned about if you're not doing something particularly sensitive.
You can use this:
int random(int min, int max){
return min + rand() / (RAND_MAX / (max - min + 1) + 1);
}
From the:
comp.lang.c FAQ list · Question 13.16
Q: How can I get random integers in a certain range?
A: The obvious way,
rand() % N /* POOR */
(which tries to return numbers from 0 to N-1) is poor, because the
low-order bits of many random number generators are distressingly
non-random. (See question 13.18.) A better method is something like
(int)((double)rand() / ((double)RAND_MAX + 1) * N)
If you'd rather not use floating point, another method is
rand() / (RAND_MAX / N + 1)
If you just need to do something with probability 1/N, you could use
if(rand() < (RAND_MAX+1u) / N)
All these methods obviously require knowing RAND_MAX (which ANSI #defines in <stdlib.h>), and assume that N is much less than RAND_MAX. When N is close to RAND_MAX, and if the range of the random number
generator is not a multiple of N (i.e. if (RAND_MAX+1) % N != 0), all
of these methods break down: some outputs occur more often than
others. (Using floating point does not help; the problem is that rand
returns RAND_MAX+1 distinct values, which cannot always be evenly
divvied up into N buckets.) If this is a problem, about the only thing
you can do is to call rand multiple times, discarding certain values:
unsigned int x = (RAND_MAX + 1u) / N;
unsigned int y = x * N;
unsigned int r;
do {
r = rand();
} while(r >= y);
return r / x;
For any of these techniques, it's straightforward to shift the range,
if necessary; numbers in the range [M, N] could be generated with
something like
M + rand() / (RAND_MAX / (N - M + 1) + 1)
(Note, by the way, that RAND_MAX is a constant telling you what the
fixed range of the C library rand function is. You cannot set RAND_MAX
to some other value, and there is no way of requesting that rand
return numbers in some other range.)
If you're starting with a random number generator which returns
floating-point values between 0 and 1 (such as the last version of
PMrand alluded to in question 13.15, or drand48 in question
13.21), all you have to do to get integers from 0 to N-1 is
multiply the output of that generator by N:
(int)(drand48() * N)
Additional links
References: K&R2 Sec. 7.8.7 p. 168
PCS Sec. 11 p. 172
Quote from: http://c-faq.com/lib/randrange.html
check here
http://c-faq.com/lib/randrange.html
For any of these techniques, it's straightforward to shift the range, if necessary; numbers in the range [M, N] could be generated with something like
M + rand() / (RAND_MAX / (N - M + 1) + 1)
Taking the modulo of the result, as the other posters have asserted will give you something that's nearly random, but not perfectly so.
Consider this extreme example, suppose you wanted to simulate a coin toss, returning either 0 or 1. You might do this:
isHeads = ( rand() % 2 ) == 1;
Looks harmless enough, right? Suppose that RAND_MAX is only 3. It's much higher of course, but the point here is that there's a bias when you use a modulus that doesn't evenly divide RAND_MAX. If you want high quality random numbers, you're going to have a problem.
Consider my example. The possible outcomes are:
rand()
freq.
rand() % 2
0
1/3
0
1
1/3
1
2
1/3
0
Hence, "tails" will happen twice as often as "heads"!
Mr. Atwood discusses this matter in this Coding Horror Article
The naive way to do it is:
int myRand = rand() % 66; // for 0-65
This will likely be a very slightly non-uniform distribution (depending on your maximum value), but it's pretty close.
To explain why it's not quite uniform, consider this very simplified example:
Suppose RAND_MAX is 4 and you want a number from 0-2. The possible values you can get are shown in this table:
rand() | rand() % 3
---------+------------
0 | 0
1 | 1
2 | 2
3 | 0
See the problem? If your maximum value is not an even divisor of RAND_MAX, you'll be more likely to choose small values. However, since RAND_MAX is generally 32767, the bias is likely to be small enough to get away with for most purposes.
There are various ways to get around this problem; see here for an explanation of how Java's Random handles it.
rand() will return numbers between 0 and RAND_MAX, which is at least 32767.
If you want to get a number within a range, you can just use modulo.
int value = rand() % 66; // 0-65
For more accuracy, check out this article. It discusses why modulo is not necessarily good (bad distributions, particularly on the high end), and provides various options.
As others have noted, simply using a modulus will skew the probabilities for individual numbers so that smaller numbers are preferred.
A very ingenious and good solution to that problem is used in Java's java.util.Random class:
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while (bits - val + (n-1) < 0);
return val;
}
It took me a while to understand why it works and I leave that as an exercise for the reader but it's a pretty concise solution which will ensure that numbers have equal probabilities.
The important part in that piece of code is the condition for the while loop, which rejects numbers that fall in the range of numbers which otherwise would result in an uneven distribution.
double scale = 1.0 / ((double) RAND_MAX + 1.0);
int min, max;
...
rval = (int)(rand() * scale * (max - min + 1) + min);
Updated to not use a #define
double RAND(double min, double max)
{
return (double)rand()/(double)RAND_MAX * (max - min) + min;
}
If you don't overly care about the 'randomness' of the low-order bits, just rand() % HI_VAL.
Also:
(double)rand() / (double)RAND_MAX; // lazy way to get [0.0, 1.0)
This answer does not focus on the randomness but on the arithmetic order.
To get a number within a range, usually we can do it like this:
// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin + f * (aMax - aMin);
However, there is a possibility that (aMax - aMin) overflows. E.g. aMax = 1, aMin = -DBL_MAX. A safer way is to write like this:
// the range is between [aMin, aMax]
double f = (double)rand() / RAND_MAX;
double result = aMin - f * aMin + f * aMax;
Based on this concept, something like this may cause a problem.
rand() % (max_number + 1 - minimum_number) + minimum_number
// 1. max_number + 1 might overflow
// 2. max_number + 1 - min_number might overflow
if you care about the quality of your random numbers don't use rand()
use some other prng like http://en.wikipedia.org/wiki/Mersenne_twister or one of the other high quality prng's out there
then just go with the modulus.
Just to add some extra detail to the existing answers.
The mod % operation will always perform a complete division and therefore yield a remainder less than the divisor.
x % y = x - (y * floor((x/y)))
An example of a random range finding function with comments:
uint32_t rand_range(uint32_t n, uint32_t m) {
// size of range, inclusive
const uint32_t length_of_range = m - n + 1;
// add n so that we don't return a number below our range
return (uint32_t)(rand() % length_of_range + n);
}
Another interesting property as per the above:
x % y = x, if x < y
const uint32_t value = rand_range(1, RAND_MAX); // results in rand() % RAND_MAX + 1
// TRUE for all x = RAND_MAX, where x is the result of rand()
assert(value == RAND_MAX);
result of rand()
2 cents (ok 4 cents):
n = rand()
x = result
l = limit
n/RAND_MAX = x/l
Refactor:
(l/1)*(n/RAND_MAX) = (x/l)*(l/1)
Gives:
x = l*n/RAND_MAX
int randn(int limit)
{
return limit*rand()/RAND_MAX;
}
int i;
for (i = 0; i < 100; i++) {
printf("%d ", randn(10));
if (!(i % 16)) printf("\n");
}
> test
0
5 1 8 5 4 3 8 8 7 1 8 7 5 3 0 0
3 1 1 9 4 1 0 0 3 5 5 6 6 1 6 4
3 0 6 7 8 5 3 8 7 9 9 5 1 4 2 8
2 7 8 9 9 6 3 2 2 8 0 3 0 6 0 0
9 2 2 5 6 8 7 4 2 7 4 4 9 7 1 5
3 7 6 5 3 1 2 4 8 5 9 7 3 1 6 4
0 6 5
Just using rand() will give you same random numbers when running program multiple times. i.e. when you run your program first time it would produce random number x,y and z. If you run the program again then it will produce same x,y and z numbers as observed by me.
The solution I found to keep it unique every time is using srand()
Here is the additional code,
#include<stdlib.h>
#include<time.h>
time_t t;
srand((unsigned) time(&t));
int rand_number = rand() % (65 + 1 - 0) + 0 //i.e Random numbers in range 0-65.
To set range you can use formula : rand() % (max_number + 1 - minimum_number) + minimum_number
Hope it helps!
You can change it by adding a % in front of the rand function in order to change to code
For example:
rand() % 50
will give you a random number in a range of 50. For you, replace 50 with 63 or 127
I think the following does it semi right. It's been awhile since I've touched C. The idea is to use division since modulus doesn't always give random results. I added 1 to RAND_MAX since there are that many possible values coming from rand including 0. And since the range is also 0 inclusive, I added 1 there too. I think the math is arranged correctly avoid integer math problems.
#define MK_DIVISOR(max) ((int)((unsigned int)RAND_MAX+1/(max+1)))
num = rand()/MK_DIVISOR(65);
Simpler alternative to #Joey's answer. If you decide to go with the % method, you need to do a reroll to get the correct distribution. However, you can skip rerolls most of the time because you only need to avoid numbers that fall in the last bucket:
int rand_less_than(int max) {
int last_bucket_min = RAND_MAX - RAND_MAX % max;
int value;
do {
value = rand();
} while (last_bucket_min <= value);
return value % max;
}
See #JarosrawPawlak's article for explanation with diagrams: Random number generator using modulo
In case of RAND_MAX < max, you need to expand the generator: Expand a random range from 1–5 to 1–7
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // this line is necessary
int main() {
srand(time(NULL)); // this line is necessary
int random_number = rand() % 65; // [0-64]
return 0;
}
Foy any range between min_num and max_num:
int random_number = rand() % (max_num + 1 - min_num) + min_num;

Resources