如何使用文件在 C 编程中计算 0 到 100 之间的随机数之和?
在这个程序中,我们添加了在 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]; }
首先,我们计算随机数的和,并将该和存储在文件中。为此,采用写入打开方式打开文件,然后使用 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.
广告