이 프로그램에서는 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\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.