Maison  >  Article  >  développement back-end  >  Comment calculer la somme de nombres aléatoires entre 0 et 100 à l’aide d’un fichier en programmation C ?

Comment calculer la somme de nombres aléatoires entre 0 et 100 à l’aide d’un fichier en programmation C ?

PHPz
PHPzavant
2023-08-28 18:41:061495parcourir

Comment calculer la somme de nombres aléatoires entre 0 et 100 à l’aide d’un fichier en programmation C ?

Dans cette application, nous ajoutons des nombres aléatoires générés entre 0 et 100.

Après chaque exécution, le résultat de la somme de nombres aléatoires est différent, c'est-à-dire que nous obtenons des résultats différents à chaque fois que nous l'exécutons.

La logique que nous utilisons pour calculer la somme des nombres aléatoires entre 0 et 100 est -

for(i = 0; i <=99; i++){
   // Storing random numbers in an array.
   num[i] = rand() % 100 + 1;
   // calculating the sum of the random numbers.
   sum+= num[i];
}

Tout d'abord, nous calculons la somme des nombres aléatoires et stockons cette somme dans un fichier. Pour le fichier ouvert en écriture, ouvrez et utilisez fprintf pour ajouter la somme au fichier tableau.

fprintf(fptr, "Total sum of the array is %d</p><p>", sum);
//appending sum to the array file.

Exemple

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define max 100
// Declaring the main function in the main header.
int main(void){
   srand(time(0));
   int i;
   int sum = 0, num[max];
   FILE *fptr;
   // Declaring the loop to generate 100 random numbers
   for(i = 0; i <=99; i++){
      // Storing random numbers in an array.
      num[i] = rand() % 100 + 1;
      // calculating the sum of the random numbers.
      sum+= num[i];
   }
   // intializing the file node with the right node.
   fptr = fopen("numbers.txt", "w");
   // cheching if the file pointer is null, check if we are going to exit or not.
   if(fptr == NULL){
      printf("Error!");
      exit(1);
   }
   fprintf(fptr, "Total sum of the array is %d</p><p>", sum); // appending sum to the array file.
   fclose(fptr); // closing the file pointer
}

Sortie

Run 1: Total sum of the array is 5224
Run 2: Total sum of the array is 5555
Note: after executing a text file is created in the same folder with number.txt
We have to open it; there we can see the sum of random numbers.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer