如何使用 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.
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下