
在这个程序中,我们添加了 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];
}首先,我们计算随机数的总和并将该总和存储在文件中。对于 write open 中打开的文件,并使用 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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号