P
pembed2003
Hi All,
I hope I am posting a C question instead of a C++ this time. I have
the following program:
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
int main(int argc,char** argv){
int i;
srand(time(0));
for(i = 0; i < 20; i++){
int x = 1 + (int) (20.0 * rand() / (RAND_MAX + 1.0));
int y = 1 + (int) (20 * rand() / (RAND_MAX + 1.0));
int z = 1 + (int) (20.0 * rand() / (RAND_MAX + 1 ));
printf("%d %d %d\n",x,y,z);
}
}
and it prints:
12 1 -18
4 1 -17
14 1 -12
17 1 -13
8 1 0
9 1 -2
.... etc
it looks like x is always between 1 and 20. y is always 1 and z is
always between negative and 0. i don't understand why. i guess i
understand why x is always positive because the whole expression is
evaluated in long(?) so there won't be any overflow, right? But is y
and z behave so differently? I though C promote the expression if one
of them is long instead of int, right? Can someone explain what
happened? Thanks!
I hope I am posting a C question instead of a C++ this time. I have
the following program:
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<time.h>
int main(int argc,char** argv){
int i;
srand(time(0));
for(i = 0; i < 20; i++){
int x = 1 + (int) (20.0 * rand() / (RAND_MAX + 1.0));
int y = 1 + (int) (20 * rand() / (RAND_MAX + 1.0));
int z = 1 + (int) (20.0 * rand() / (RAND_MAX + 1 ));
printf("%d %d %d\n",x,y,z);
}
}
and it prints:
12 1 -18
4 1 -17
14 1 -12
17 1 -13
8 1 0
9 1 -2
.... etc
it looks like x is always between 1 and 20. y is always 1 and z is
always between negative and 0. i don't understand why. i guess i
understand why x is always positive because the whole expression is
evaluated in long(?) so there won't be any overflow, right? But is y
and z behave so differently? I though C promote the expression if one
of them is long instead of int, right? Can someone explain what
happened? Thanks!