Reputation: 65
I have two arrays of 10 numbers containing random floating numbers between 0 to 1. Let's say a[10]
and b[10]
. I am now generating a random floating point number between between 0 and 1 in a variable c
using the first for
loop and then comparing it with 'b' in a 2nd for
loop.
When the condition is true the 2nd for
loop should stop and go back to the previous for
loop to generate the next random number. The problem is that I have tried several methods ( increasing k to max limit in if condition or break
function or goto
function to exit from 2nd for
loop when the condition is true but none of them is working correctly and sometimes gives me a garbage value.
It is obvious that the random number will be smaller or equal to the 'b' at some points because both have numbers between 0 to 1.
int d;
float e[10];
a={0.3,0.9,1,0.2,0.11,0.21,0.43,0.64,0.55,0.88};
b={0.4,0.7,0.78,0.11,0.49,0.2,0.13,0.74,0.65,0.98};
for (int j=0; j<10; j++) //first for loop for generating random number
{
float c=(float)rand()/((float)RAND_MAX);
for (k=0; k<10; k++) // 2nd for loop for comparison with generated number
{
if (c<=b)
{
d=k;
e[k]=a[d];
printf("%f\n",e);
k=10;
//goto jmp;
//break;
}
}
//jmp: printf("\n");
}
Upvotes: 1
Views: 177
Reputation: 106042
Your declaration for array a
and b
of 10 float
s
a={0.3,0.9,1,0.2,0.11,0.21,0.43,0.64,0.55,0.88};
b={0.4,0.7,0.78,0.11,0.49,0.2,0.13,0.74,0.65,0.98};
is wrong (specially in C). Change this to
float a[10]={0.3,0.9,1,0.2,0.11,0.21,0.43,0.64,0.55,0.88};
float b[10]={0.4,0.7,0.78,0.11,0.49,0.2,0.13,0.74,0.65,0.98};
Now you can't do if (c<=b)
.b
is an array of float
and c
is a float
type. No comparison like this is possible in C.
I think you wanted to do this
if (c<=b[j])
{
....
printf("%f\n",e[k]);
....
}
Upvotes: 0
Reputation:
By mentioning the name of the array (in your case e
), it will give you the address. (Array's in some cases decays to pointers)
You have to use e[k] to print the float value.
if (c<=b[j])// Here, I have changed it
{ ^-- error was here
...
...
printf("%f\n",e[k]);// Here, I have changed it
^-- error was here
Upvotes: 0
Reputation: 4951
I think this condition is wrong:
if (c<=b)
since your variable declarations are:
float c;
float b[10] = {....};
So probably you want to do something like
if (c<=b[0])
{
....
break;
}
Upvotes: 1