+ 2
Randomize
Is it possible to randomize the numbers: 4,9,16,24,36 with random function in C?
15 Antworten
+ 6
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int getRand(void){
static int is_init = 0;
int r;
if(!is_init){
srand(time(0));
is_init = 1;
}
r = rand()%5 + 2;
return r*r - (r==5);
}
int main(){
int i;
for(i = 0; i < 10; ++i)
printf("%d\n",getRand());
return 0;
}
+ 7
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
unsigned tab[] = {4,9,16,24,36};
unsigned i,j;
srand(time(0));
for(i = 0; i < 5; ++i){
j = rand()%5;
tab[i]^=tab[j]^=tab[i]^=tab[j]; /* swapping tab[i] and tab[j] */
}
for(i = 0; i < 5; ++i)
printf("%u ",tab[i]);
putchar('\n');
return 0;
}
+ 5
@Joseph, I do not understand what you said. I am not struggling with C++ but having fun with it, and much more with C !
There are languages more useful than C++ ? Depends on what you like to do :p
+ 2
Yeees @~ swim ~ ! I forgot to set is_init to 1 ! I correct it right away
+ 2
English is not my mother language. I am trying to develop my english. That is why I cannot make sentences that are meaningful. Sorry for that. @Baptiste
+ 2
Oh no @Joseph, sorry I did not mean that ! I mean to say that for me, you do not struggle to program, you have fun doing it ! So I did not understand this feeling, rather ^^
+ 2
I understand now. :D @Baptiste
+ 1
Thank you. But I forget to say I am trying to make this program without arrays. By the way, What are you doing with C++? You are really struggling with C++. But I think there are other languages that are much more useful than C++. @Baptiste
+ 1
What is the reason for not using an array? If not using arrays what other option are accepted? The easiest would be to store the numbers in an array and randomly choose numbers from the array. Otherwise in C++ deque, vector, list, set, or map might be made to work. I have not studied C so not sure how much of C++ works in C.
+ 1
Because in my education system, I cannot use what I have not learn. That is why I am not using arrays. I can use variables, loops, math.h, functions. I know it does not make sense but I have to.
@Bob
+ 1
This is quite long. May be a shorter way to do this within your requirement.
https://code.sololearn.com/cGbPoMaN3NDC/?ref=app
+ 1
In the question is that supposed to be 24 or 25?