Storing a Randomly generated number in a variable - c

Im trying to make a program that calculates out a math equation, Im getting stuck on how i generate a random number from 0.00 to 1.00 and store it in a variable a.
this is my code so far, im stuck to how now take that number and store it for future use. I need to store that random number in a, and hten use it in a loop, and then generate a new random number and use it in the 2nd cycle of the loop.
EDIT
this is what i have been working on now, it is suppose to calculate the number of times a random number is inside the area, count it, and then devide by the number of times run, but im not getting any output
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
int n = 10;
float x;
float y;
float pi = 3.1415;
float rootxy;
initrand();
int z = 0;
int inside = 0;
x = randfloat();
y = randfloat();
float area = 0.25 * pi;
float calculatedpi;
rootxy = sqrt(pow(x,2) + (pow(y,2)));
while (z < n){
if (rootxy > area) {
inside++;
z++;
}
else{
return 0;
}
calculatedpi = (inside/n);
}
printf("%f", calculatedpi);
}

There are a few issues with your code:
You shouldn't use nested functions. Some compilers support them as an extension but it's not standard. Define randfloat and initrand outside main
The function initrand does too little. Why not call srand((time(0)); from main ?
Your initrand function is declared as returning a double but it doesn't return anything (and the way it's named it shouldn't). If you need to use such a function, why not make it return void ?
You should rarely use float. Why not use double ?
That said, you can do this to store that random value:
double randdouble()
{
return rand()/((double)RAND_MAX + 1);
}
int main()
{
double x = randdouble();
/* ... */
}

I think you want something like this:
#include <stdlib.h>
#include <time.h>
void initrand(void)
{
srand(time(0));
}
float randfloat(void)
{
return rand()/(float)RAND_MAX;
}
int main(void)
{
initrand();
float a = randfloat();
return 0;
}
You can't nest functions like in some other languages.
You had non-matching parentheses in the initrand function.
I fixed the declarations of your functions, use void when there are no parameters, initrand doesn't return anything.
Your division by RAND_MAX+1 was a little messed up. Simply divide by RAND_MAX and the result will be in the closed interval [0,1]. And the syntax for the conversion to float was not quite right.

If you want to get random double numbers in a specified range you can use this function
// Return a random double from a to b
double randomDouble(double a, double b)
{
return = ( rand() / ( (double)RAND_MAX + 1.0))
* (b - a) + a;
}

Related

Calculating $\sqrt[3]{x}$ with Babylonian method

Consider my attempt to implement the Babylonian method in C:
int sqrt3(int x) {
double abs_err = 1.0;
double xold = x;
double xnew = 0;
while(abs_err > 1e-8) {
xnew = (2 * xold + x/(xold* xold))/3;
abs_err= xnew-xold;
if (abs_err < 0) abs_err = -abs_err;
xold=xnew;
}
return xnew;
}
int main() {
int a;
scanf("%d", &a);
printf(" Result is: %f",sqrt3(a));
return 0;
}
Result is for x=27: 0.0000?
Where is my mistake?
While the function returns an int, that value is printed with the wrong format specifier, %f instead of %d.
Change the signature (and the name, if I may) into something like this
double cube_root(double x) { ... }
Or change the format specifier, if you really want an int.
Following the explanation from tutorialspoint, which states, that the basic idea is to implement the Newton Raphson method for solving nonlinear equations, IMHO, the code below displays this fact more clearly. Since there is already an accepted answer, I add this answer just for future reference.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
double rootCube( double a)
{
double x = a;
double y = 1.0;
const double precision = 0.0000001;
while(fabs(x-y) > precision)
{
x = (x + y) / 2.0;
y = a / x / x;
}
return x;
}
int main(int argc, const char* argv[])
{
if(argc > 1)
{
double a =
strtod(argv[1],NULL);
printf("cubeRoot(%f) = %f\n", a, rootCube(a));
}
return 0;
}
Here, in contrast to the original code of the question, it is more obvious, that x and y are the bounds, which are being improved until a sufficiently accurate solution is found.
With modification of the line in the while block, where y is being updated, this code can also be used to solve similar equations. For finding the square root, for example, this line would look like this: y = a / x.

What is the difference between using/not using return in a subprogram?

The second piece of code is not giving the correct value as it only passes the value of r from what I see. However, I would like to make this code work without using return (just for learning how to do it in this other way). Also, what is considered best practice between these two options? Thank you! :-)
#include <stdio.h>
#define PI 3.1416
float area(float r);
int main(void)
{
float r = 10;
printf("Area: %.2f", area(r));
return 0;
}
float area(float r) {
return PI * r * r;
}
#include <stdio.h>
#define PI 3.1416
float area(float r);
int main(void)
{
float r = 10;
printf("Area: %.2f", area(r));
return 0;
}
float area(float r) {
PI * r * r;
}
I would like to make this code work without using return (just for learning how to do it in this other way).
Using return is the only way to actually return a value from a function.
However, the C syntax provides two alternative options:
It is possible to pass another pointer as argument to the function, which points to an object in the caller, in which you then assign the value of the expression.
For example:
#include <stdio.h>
#define PI 3.1416
void area(float r, float *p);
int main(void)
{
float r = 10;
float s;
area(r, &s);
printf("Area: %.2f", s);
return 0;
}
void area(float r, float* p) {
*p = PI * r * r;
return;
}
It is also possible to define a global object and assign the value of the expression to that global object instead.
For example:
#include <stdio.h>
#define PI 3.1416
float s;
void area(float r);
int main(void)
{
float r = 10;
area(r);
printf("Area: %.2f", s);
return 0;
}
void area(float r) {
s = PI * r * r;
return;
}
But that is considered to be bad practice because the connections from and to the function and with that the actual use of the function are then much harder to understand than using parameters and return types, which on the other hand show the relation and the use of the particular function call pretty good.
The use of global objects shall be avoided if possible although there are cases where a global objects is suitable, if you f.e. use an object in multiple functions and the role of the object is exactly defined. But in the provided example of yours, a global object does not fit very well and shall be avoided.
If no value shall be returned, define the return type of the function as of type void.

Can't get random numbers in c

I am trying to get two random numbers between 0 and 11 but i get the same number whenever i execute my code. These numbers are 7 and 10. Here is my code:
void track_machine(){
int X = 0,Y = 0; //Coordinates
double D = 0,R = 0; //Distance and replacement
refresh_position(&X,&Y,&D,&R);
printf("%d\n",X);
printf("%d\n",Y);
}
void refresh_position(int *X, int *Y, double *D, double *R){
*X = rand()%12;
*Y = rand()%12;
}
With
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
call srand(time(NULL)); at the start of your program - before you use rand() - to set a different seed every time.
The "random-number-generator" is, despite its name, still a deterministic algorithm. When starting with the same seed values (when srand is not called), it will always produce the same results.

Function to calculate Pi in C

I'm trying to code a formula where the user inputs a number n to calculate Pi using Pi= n^2/(n-1)(n+1). But for some reason the output is wrong. I don't know if my math is wrong or there's something wrong with the function.
Here is the code :
#include <stdio.h>
#include <math.h>
double pi_array (int n)
{
int i;
double a;
if (n%2==0)
{
for (i=2;i<=n;i+=2)
{
a=pow(n,2)/((n-1)*(n+1));
}
}
return a;
}
double pi_value (int n)
{
int i;
double pi;
for (i=0;i<=n;i++)
{
pi=pi_array(n);
}
return pi;
}
void main()
{
int n;
scanf("%d",&n);
printf ("%lf\n", pi_value(n));
}
Just like #Mat pointed out, in this part of your code:
for (i=2;i<=n;i+=2)
{
a=pow(n,2)/((n-1)*(n+1));
}
It is doing the same computation again and again because n does not change its value. The answer pow(n,2)/((n-1)*(n+1)) remains the same even for all the iterations.
Also, on a side note, what formula are you using to calculate your answer? If you put n = 4, you get the value as 16/15 which equals 1.0667. For n = 5, the asnwer is 1.041667. They are clearly not equal to pi. I think thew formula might be wrong itself. You could post the question about the formula on MathStackExchange to get an idea of what the exact formula is, and then implement it in C later :).
Best.

How can I use two random numbers generated in a function as matrix coordinates?

I came up with this function to generate two random numbers, r and c, so that I can use them in as coordinates in matrix board[r][c]. Is this even possible?
int coordAleatoria()
{
srand((unsigned int)time(0));
int r=rand()%9;
int c=rand()%9;
while(r==c)
{
c=rand()%9;
}
printf("%d %d", r, c);
return r;
return c;
}
This is for a chess-like game. The PC is supposed to generate random moves. This function does generate coordinates, I'm just not sure how to make my program treat them as coordinates.
I hope I can get r and c in board[r][c] to be the values generated in coordAleatoria().
You cannot return more than one time. So you can combine the coordinates using structure as Jabberwocky suggested in the comment. If you are still finding it difficult than here is the implementation.
#include<stdio.h>
#include<stdlib.h>//for rand()
#include<time.h>//for time()
struct Pair
{
int row,col;
};
struct Pair coordAleatoria()
{
int r=rand()%9;
int c=rand()%9;
while(r==c)
{
c=rand()%9;
}
printf("Inside function: row=%d and col=%d\n",r,c);
//Create a pair
struct Pair p;
//Assign values
p.row=r,p.col=c;
//return it
return p;
}
int main()
{
srand((unsigned int)time(0));
//Get the returned value as a Pair
struct Pair p=coordAleatoria();
//Collect the row and column values
int r=p.row;
int c=p.col;
//Now you can use them here
printf("Outside function: row=%d and col=%d\n",r,c);
}
rand()%9 generates 9 different values. With while(r==c), looks like code is looking for 9*(9-1) or 72 different pairs. For a speedier approach, call rand() once.
Code could return a single int and later divine/mod by 9 to recover the row/column.
srand((unsigned int)time(0)); should not be repeated called in coordAleatoria(). Call it once, perhaps in main().
int coordAleatoria(void) {
int rc = rand()%72;
int r = rc/9;
int c = rc%9;
if (r==c) r++;
return (r*9) + c;
}
Rather than calling rand() twice (after properly seeding the random number generator with a call to srand()), you can simply call rand() once and take the first two digits as your coordinates, e.g.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
int x, y;
} pair_t;
void rand_coords (pair_t *coords)
{
int n = rand();
coords->x = n % 10;
n /= 10;
coords->y = n % 10;
}
int main (void) {
pair_t coords = { .x = 0 };
srand (time (NULL)); /* seed random number generator */
rand_coords (&coords);
printf ("coords.x : %d\ncoords.y : %d\n", coords.x, coords.y);
return 0;
}
(or take the modulo of whatever your actual coordinate range is)
Example Use/Output
$ ./bin/coords_rand
coords.x : 9
coords.y : 8
$ ./bin/coords_rand
coords.x : 1
coords.y : 1
$ ./bin/coords_rand
coords.x : 5
coords.y : 7
$ ./bin/coords_rand
coords.x : 8
coords.y : 0

Resources