如何使用 C 编程中的文件计算 0 到 100 之间的随机数的总和?
在这个程序中,我们添加了在0到100之间生成的随机数。
每次运行后,随机数之和的结果都是不同的,即每次执行都会得到不同的结果。
我们用来计算0到100之间随机数总和的逻辑是-
for(i = 0; i <=99; i++){ //将随机数存储在数组中。 num[i] = rand() % 100 + 1; //计算随机数的总和。 sum+= num[i]; }
首先,我们计算随机数的总和并将该总和存储在一个文件中。对于writeopen中的打开文件,并使用fprintf将总和附加到数组文件。
fprintf(fptr, "Total sum of the array is %d\n", sum); //appending sum to the array file.
示例
#include输出结果#include #include #define max 100 //Declaringthemainfunctioninthemainheader. int main(void){ srand(time(0)); int i; int sum = 0, num[max]; FILE *fptr; //Declaringthelooptogenerate100randomnumbers for(i = 0; i <=99; i++){ //将随机数存储在数组中。 num[i] = rand() % 100 + 1; //计算随机数的总和。 sum+= num[i]; } //intializingthefilenodewiththerightnode. fptr = fopen("numbers.txt", "w"); //chechingifthefilepointerisnull,checkifwearegoingtoexitornot. if(fptr == NULL){ printf("Error!"); exit(1); } fprintf(fptr, "Total sum of the array is %d\n", sum); //appendingsumtothearrayfile. fclose(fptr); //closingthefilepointer }
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.