我很难理解如何抓住我想要的数字,
for (i = 0; i<n; i++)
我看到这个数字每次增加1,直到它到达i的输入,然而,让我们说我想得到这些数字的总和或平均值。我如何拉出每个数字并添加它们,因为int r每次都会更改为下一个rand整数?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXN 1000
#define MIN 0
int main(void) {
int n, r, i;
int pos = 0;
int minpos = 0;
int max, min;
int num[MAXN];
float sum = 0.0, average;
printf("Enter an integer");
scanf("%d", &n);
srand(time(0));
printf("\n Pos | Val"); //setting up Pos/Val table
for (i = 0; i<n; i++)
{
r = (int)(((double)rand() / RAND_MAX) * 1000) + 1;
printf("\n %3d | %3d", i + 1, r);
num[i] = r;
}
printf("\n");
max = num[0]; //finding the maximum number
i = 1;
for (i = 1; i < n; i++)
{
if (num[i] > max)
{
max = num[i];
pos = i;
}
}
min = num[0]; //finding the minimum number
i = 1;
for (i = 1; i < n; i++)
{
if (num[i] < min)
{
min = num[i];
minpos = i;
}
}
printf("\nMax : %d | Pos : %d", max, pos + 1); //biggest number
//while (1);
printf("\nMin : %d | Pos : %d", min, minpos + 1); //smallest number
return 0;
}
输出:
Enter an integer 5
Pos | Val
1 | 493
2 | 774
3 | 62
4 | 896
5 | 183
Max : 896 | Pos : 4
Min : 62 | Pos : 3