>  기사  >  백엔드 개발  >  C 프로그래밍에서 파일을 사용하여 0에서 100 사이의 난수 합계를 계산하는 방법은 무엇입니까?

C 프로그래밍에서 파일을 사용하여 0에서 100 사이의 난수 합계를 계산하는 방법은 무엇입니까?

PHPz
PHPz앞으로
2023-08-28 18:41:061495검색

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</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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제