Keith said:
RAND_MAX is of type int. 1.0 is of type double. The "usual
arithmetic conversions" are applied to the operands (C99 6.5.6p4).
These are described in 6.3.1.8. RAND_MAX is converted from int to
double, and the addition yields a double result.
Grab a copy of <
http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf>
if you haven't already. Or any decent C reference should explain it.
Something else I just thought of: An alternative to
(RAND_MAX + 1.0)
would be
(double)(RAND_MAX + 1)
The version with 1.0 has two advantages that I can think of:
it avoids the need for a cast, and it avoids integer overflow if
RAND_MAX == INT_MAX.
I'm not sure that does what you think it does:
dan@dan-desktop:~/source$ gcc -std=c99 -Wall -Wextra mort7.c -o out; ./out
mort7.c: In function ‘main’:
mort7.c:35: warning: integer overflow in expression
mort7.c:22: warning: unused variable ‘g’
mort7.c:21: warning: unused variable ‘k’
mort7.c:21: warning: unused variable ‘i’
3908406666 = 00010111010010111100000101011010
-2147483648.0000006 =
1100000111100000000000000000000000000000000000000000000000000000
dan@dan-desktop:~/source$ cat mort7.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <limits.h>
#define STRING "%7d6 = %s\n"
#define E_TYPE int
#define F_TYPE double
#define STRING2 "%7f6 = %s\n"
#define N 26
typedef E_TYPE e_type;
typedef F_TYPE f_type;
void bitstr (char *str, const void *obj, size_t n);
int
main (void)
{
int i, j, k;
double g;
e_type e;
f_type f;
char ebits[CHAR_BIT * sizeof e + 1];
char fbits[CHAR_BIT * sizeof f + 1];
srand (time (NULL));
j = rand ();
e = j;
bitstr (ebits, &e, sizeof e);
printf (STRING, e, ebits);
f = (double)(RAND_MAX + 1);
bitstr (fbits, &f, sizeof f);
printf (STRING2, f, fbits);
return 0;
}
void
bitstr (char *str, const void *obj, size_t n)
{
unsigned mask;
const unsigned char *const byte = obj;
while (n-- != 0)
{
mask = ((unsigned char) -1 >> 1) + 1;
do
{
*str++ = (char) (mask & byte[n] ? '1' : '0');
mask >>= 1;
}
while (mask != 0);
}
*str = '\0';
}
// gcc -std=c99 -Wall -Wextra mort7.c -o out; ./out
dan@dan-desktop:~/source$
I think we all agree that none of these values are to be negative.