It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Most modern computers exhibit non deterministic behavior, what makes impossible to tell how many clock cycles will occur between two consecutive calls to read the computer clock.
The following code is a pseudo random number generator for one byte using the computer clock.
unsigned long occurrences = 0;
unsigned long total = 0;
while (true) {
if ((clock() & 0xFF) == 60) // testing ocurrences for a given number, 60 for instance
occurrences++;
total++;
printf("%f\n", (float)occurrences / (float)total ); // this should be approximately 1/256 = 0.00390625
}
Excluding serious applications like encription for instance, it could be used in mobile platforms for games.
I wonder what could be the advantages and disadvantages of such implementation.
You are missing the proper way to use rand() or, more specifically, srand().
You need to call srand() exactly once during program run.
Do not call srand() in a loop.
Do not call srand() before each call to rand().
The best way to ensure proper srand() management is to call it once inside your main() function and then forget about it: just use rand() afterwards.
#include <stdlib.h> /* rand, srand */
#include <time.h> /* time */
int main(void) {
/* initialization */
srand(time(NULL));
/* input, possibly calling rand() */
/* process, possibly calling rand() */
/* output, possibly calling rand() */
/* termination */
return 0;
}
You should do the "splitting" using a union instead of pointers like that.
And i agree that random numbers and clock are two completely different things, and you made more of a statement than asking a question.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a simple first order transfer such as "3/s+3" or "tf(3,[1 3])" function and I would like to implement in c code. I have a C function that is called with the delta time since the last iteration:
double output(double input, double t); //usually, t is around 0.01 second
How do implement the transfer function 3/s+3 in C?
It's not just a matter of implementing 3/(s+3) directly.
You need to discretize it to the z-domain using an appropriate technique (forward euler, backward euler, tustin, zero-order hold) then implement the discrete version of the filter.
The following would be a simple version for the Tustin transformation.
As written, the state needs to be initialized and stored somewhere externally to this function.
double firstOrderLag(double input, double coeff, double dT, double *state){
// Function to implement the discretization of a continuous time first
// order lag sys = coeff/(s+coeff) using the Tustin (Bilinear) transformation.
double num = (1/(1+2/coeff/dT)); // numerator
double den = (1-2/coeff/dT)*num; // denominator
double temp;
double output;
temp = input - den*(*state);
output = num*(temp + (*state));
*state = temp;
return output;
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
weather.outdooe_temp is a float value which is being updated every time I press a button. set_temp is a float to ascii function. If I use that the thing works, but not if I use the code below.
char Thermo_Buff66[4];
static void SetBox(ScreenObj_t const *pS, EVENT_MSG const *pMsg)
{
//set_temp(weather.outdoor_temp,&a);//it works if i use this function.
sprintf(Thermo_Buff66,"%2.1f",weather.outdoor_temp);
(void)sprintf(Thermo_Buff,"%s\xc2\xb0""",Thermo_Buff66);
(void)DataBoxHandler(pS, &msg, "Set Temp", (uint8_t *)Thermo_Buff);
//currently displaying any # value....!!ing!!
}
char Thermo_Buff66[4];
sprintf(Thermo_Buff66,"%2.1f",weather.outdoor_temp);
The buffer you have allocated (Thermo_Buff66) is too short for a floating number representing outdoor temperature (often 2 digits) plus a . plus a digit after. Indeed, it doesn't have space for the terminating '\0' character. So immediate correction would be to set the size to 5. Still, in case of armageddon (or simply being in a non-SI country ... cough ... US), the temperature could even get to above 100, in which case again you overflow your buffer. Do yourself a favor and use snprintf.
Regardless, you sprintf into a buffer, then using %s you sprintf it into something else, which there is no point to. You can do it all directly in one, removing Thermo_Buff66 altogether:
(void)sprintf(Thermo_Buff, "%.1f\xc2\xb0", weather.outdoor_temp);
(void)DataBoxHandler(pS, &msg, "Set Temp", (uint8_t *)Thermo_Buff);
Side note: the . and the precision digit already take up 2 characters. Setting minimum width to 2 is therefore reduntant. Perhaps you thought the 2 in %2.1 is the number of digits before the .? Well it's not. It's the minimum overall width.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
The exercise asks to find which of the numbers from 1 to 500, the sum of the numbers specific digits, raised to the third power equals that particular number.
for example 1^3=1
and 371 makes 3^3+7^3+1^3 = 371
How I approached the problem:
I was thinking if I could have an array of strings with 500 slots, each slot containing a string converted number, then I could do math with each slot's string. If they met the criteria I would apply then that slot would be printed.
I tried the function sprintf without much success. In a loop it just initializes the strings (or is it arrays? after 3 hours I am confused) [0] slot, leaving all other slots unchanged.
I don't want you to solve the exercise, rather than guide me with my logic. Please ask me to add code of what I did if you want to.
Always start by clearly defining your algorithm, so you know what you are doing. Split it up into simple steps. Something like this:
For each integer i in the interval 1 to 500:
Check if the condition holds for this i
If it holds:
Print i
else:
Do nothing
Now you need to define "Check if the condition holds for this i". I would use some modulo and division arithmetics to extract the digits, but I leave the details to you.
Note that I have talked nothing about C or any other programming language. Only when you know your algorithm should you start thinking about implementation.
(There is actually the possibility of a slightly different algorithm than the one given above, where you have one loop for each digit nested inside each other. That solution may be acceptable to you but it will not be as generic)
for(i=1;i<=500;i++)
{
//loop for checking each number i
int sum=0; // to store the sum of cube of digits
int n=i; //copy of i
//The below while loops does the task. It extracts a digit from the number and adds its cube to the sum
// last digit from the number can be seen by taking its remainder by 10 . For eg 35%10=5
//once we have used this digit make the number shorter by dividing by 10. For eg 35/10 becomes 3 (because of integer divisions)
while(n>0)
{
int rem=n%10; //extract the last digit
sum+=cube(rem); //cube function raises a number to its cube
n/=10; //remove the digit we had extracted earlier from the number
}
if(sum==i) //we got the number we wanted
printf("%d\n",i);
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Is there any way to generate a random number in C without using seed.
Here what have so far but it still using srand(time(NULL)); which is a seed.
#include <stdio.h>
#include <time.h>
#include <math.h> /* required for sqrt() */
#include <stdlib.h> /* required for rand() */
int gen_rand(); /* note these are declarations of functions */
void main()
{
int number;
srand (time(NULL)); /* everytime you run program, it will give you different result */
number = gen_rand();
printf("%d is the power of 2 of %.0lf\n", number, sqrt(number));
}
/* Function generates random number power 2 of 20 - 230 */
int gen_rand()
{
int n;
n = rand() % 211; /* n is random number in range of 0 - 210 */
n = n + 20; /* n is now in range of 20 - 230 */
return(n*n); /* return n to the power of 2 */
}
Yes and no.
There are basically two methods to get even remotely random numbers in c.
1) have a pseudo random number generator with seed -- that is an algorithm, that produces some sequence of numbers using clever arithmetic operators and possible lots of internal variables that are mixed, permuted, twisted and whatever. The seed can be implicit (i.e. always zero and each time you run the program, the same sequence is generated). Or it can be explicit, where the seed can be changed somehow between runs.
2) Using external source of data, that somehow changes in between runs. That could come from a timer, environment variables (program id perhaps), noise from camera, mouse movements etc.
1+2) use the external source of noise as seed to pseudo random number generator.
All non-hardware based PRNG require some form of random input to combat their deterministic nature, thus a seed will always be required.
You can try abuse /dev/rand under linux (but it also is a PRNG), or if you have a very modern Intel CPU, their new digital RNG facilities would work.
No. If you don't seed the automatic number generator, it will behave deterministically and yield the same numbers every time.
Yes. Generating random numbers by using the rand() function without using a seed will give you the same set of random numbers though.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I'm trying to solve the 8th problem of the project Euler and I'm stuck because I can't manage to create a very long array of char.
There must be a stupid semantic issue, but I'm unable to find it.
char cifre[] = "very long list of numbers here";
Such example works with gcc:
#include <stdio.h>
int main (void)
{
char *x =
"73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
62229893423380308135336276614282806444486645238749\
30358907296290491560440772390713810515859307960866\
70172427121883998797908792274921901699720888093776\
65727333001053367881220235421809751254540594752243\
52584907711670556013604839586446706324415722155397\
53697817977846174064955149290862569321978468622482\
83972241375657056057490261407972968652414535100474\
82166370484403199890008895243450658541227588666881\
16427171479924442928230863465674813919123162824586\
17866458359124566529476545682848912883142607690042\
24219022671055626321111109370544217506941658960408\
07198403850962455444362981230987879927244284909188\
84580156166097919133875499200524063689912560717606\
05886116467109405077541002256983155200055935729725\
71636269561882670428252483600823257530420752963450"
;
printf ("%s",x);
}
It prints your long number on screen without any problem. Symbol \ in string tells compiler that string literal is continued on next line. You are free to modify this example as you want. But please note that modifying content of string pointed by x isn't good idea.
Does adding a \ after each line of that 1000 digit number help?
It allows you to enter longer literals that span multiple lines.
Alternatively, surround each line of that long string in ", it will do the same thing.
As others have pointed out, you should probably allocate it dynamically. However, your question is somewhat vague as you didn't indicate where you are running into trouble or what your idea of "very long" is.
But here's some code to get you started:
#define ARRAY_SIZE 10240
char* pArray = (char*)malloc(ARRAY_SIZE);
memset(pArray, 0, ARRAY_SIZE);
free(pArray);