在這個程式中,我們加入了 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</p><p>", 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</p><p>", 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.
以上是如何使用C程式中的檔案計算0到100之間隨機數的總和?的詳細內容。更多資訊請關注PHP中文網其他相關文章!