首页 > 文章列表 > 如何使用C编程中的文件计算0到100之间随机数的总和?

如何使用C编程中的文件计算0到100之间随机数的总和?

随机数 文件 关键词:C编程
381 2023-08-29

在这个程序中,我们添加了 0 到 100 之间生成的随机数。

每次运行后,随机数之和的结果都是不同的,即,我们得到不同的结果每次执行。

我们用来计算 0 到 100 之间的随机数之和的逻辑是 -

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];
}

首先,我们计算随机数的总和并将该总和存储在文件中。对于 write open 中打开的文件,并使用 fprintf 将总和附加到数组文件。

fprintf(fptr, "Total sum of the array is %d

", sum); //appending sum to the array file.

示例

#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

", sum); // appending sum to the array file.    fclose(fptr); // closing the file pointer }

输出

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.