Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C Exercises: Generates 50 random numbers between -0.5 and 0.5

C Basic Declarations and Expressions: Exercise-66 with Solution

Write a C program that generates 50 random numbers between -0.5 and 0.5 and writes them in a file rand.dat. The first line of ran.dat contains the number of data and the next 50 lines contains the 50 random numbers.

Sample Solution:

C Code:

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#define N 50
int main() {
  int i;
  char str;
  FILE * fptr;
  fptr = fopen("rand.dat", "w");
  if (fptr == NULL) {
    printf("Error in creating output.dat\n");
    return 0;
  }
  srand(time(NULL));
  fprintf(fptr, "%d\n", N);
  for (i = 1; i <= N; i++) {
    fprintf(fptr, "%0.4lf\n", (rand() % 2001 - 1000) / 2.e3);
  }
  fclose(fptr);
  fptr = fopen ("rand.dat", "r");  
  str = fgetc(fptr);
	while (str != EOF)
		{
			printf ("%c", str);
			str = fgetc(fptr);
		}
  fclose(fptr);
  return 0;
}

Sample Output:

50
-0.4215
0.2620
0.3065
-0.0485
-0.2085
-0.2490
-0.2780
0.2905
-0.3120
0.1275
0.4010
0.3060
0.4680
-0.1135
0.0130
-0.0145
-0.1890
-0.3825
0.3790
-0.2370
0.0840
-0.1985
0.2065
0.4445
0.0785
-0.2370
-0.0705
0.3870
-0.4695
0.1525
0.2755
0.3880
-0.3075
-0.1400
-0.3825
-0.0155
-0.1105
-0.1605
-0.4470
0.0780
0.4675
0.2330
-0.3380
0.2135
0.3980
0.1750
0.4780
-0.2915
0.0715
0.3565

Flowchart:

C Programming Flowchart: Generates 50 random numbers between -0.5 and 0.5

C programming Code Editor:

Contribute your code and comments through Disqus.

Previous:Write a C program that accepts integers from the user until a zero or a negative number, display the number of positive values, the minimum value, the maximum value and the average of all numbers
Next: Write a C program to evaluate the equation y=xn when n is a non-negative integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



C Programming: Tips of the Day

Static variable inside of a function in C

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

Ref : https://bit.ly/3fOq7XP