Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

คำนวณผลรวมตัวเลขสุ่ม 0-100 บันทึกลงไฟล์ใน C


สร้างตัวเลขสุ่ม 100 ตัว (1-100) หาผลรวม บันทึกลงไฟล์ ทุกครั้งรันได้ค่าต่างกัน

ตรรกะ

srand(time(0));           // seed จากเวลา
for(i=0; i<100; i++) {
    num[i] = rand() % 100 + 1;  // 1-100
    sum += num[i];
}
fprintf(fp, "Total sum = %d\n", sum);

โปรแกรมตัวอย่าง

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100

int main() {
    srand(time(0));
    int i, sum = 0, num[MAX];
    FILE *fptr;
    
    for(i = 0; i < MAX; i++) {
        num[i] = rand() % 100 + 1;
        sum += num[i];
    }
    
    fptr = fopen("numbers.txt", "w");
    if (fptr == NULL) { printf("Error!"); return 1; }
    
    fprintf(fptr, "Total sum of the array is %d\n", sum);
    fclose(fptr);
    return 0;
}

ผลลัพธ์ (ตัวอย่าง)

Run 1: Total sum of the array is 5224
Run 2: Total sum of the array is 5555
Note: เปิดไฟล์ numbers.txt ในโฟลเดอร์เดียวกัน จะเห็นผลรวม