ในโปรแกรมนี้ เรากำลังเพิ่มตัวเลขสุ่มที่สร้างขึ้นระหว่าง 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]; }
ขั้นแรก เราคำนวณผลรวมของตัวเลขสุ่มและเก็บผลรวมนั้นไว้ในไฟล์ สำหรับไฟล์ที่เปิดอยู่ในการเขียน open และผนวกผลรวมเข้ากับไฟล์อาร์เรย์โดยใช้ fprintf
fprintf(fptr, "Total sum of the array is %d\n", 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\n", 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.