This question is very tricky actually. Our teacher wants us to write a program (in C) that gets an unknown amount of numbers from the user (until the user enters -1) and that counts the amount of numbers above the average WHILE INPUTING THE NUMBERS . The thing that makes this task hard is the fact that we are NOT allowed to use arrays. I tried to calculate the rate of change in the averages and come up with a conclusion about our guess regarding the amount of numbers that are no longer above the average when the user enters a certain "big" number, but nothing came up to my mind. I just don't know how this thing can be programmed without actually saving the numbers somewhere and checking them after the final number has been inputed. I don't even know if it's possible. Do you have any suggestions?
This is impossible without keeping an amount of information proportional to the number of inputs, thus essentially requiring arrays.
Proof: Consider any sequence of n −1 inputs followed by a final input x . For illustration, suppose the set of allowed inputs is the rational numbers. By selecting x , we can make the average any rational number. (If the sum of the first n −1 inputs is s and we want the average to be a , then we select x = an − s .) So, we can select an x that is very slightly below 1 and that is very slightly above 1, and therefore the program must “know” whether 1 is in the prior inputs so that it can be included in the count. Similarly, we can select an x that is very slightly below or above any other number, and the program must respond accordingly. So the only way for the program to be able to produce a correct count for all possible inputs is if it has a record of all prior inputs.
I believe that teacher is trying to teach you how to use malloc
family functions.
I would do it this way:
typedef struct
{
size_t size;
int data[];
}data_type;
size_t countAbove(const data_type *data, int val)
{
size_t count = 0;
for(size_t i = 0; i < data -> size; i++) count += data -> data[i] > val;
return count;
}
int getAverage(const data_type *data)
{
long long sum = 0;
for(size_t i = 0; i < data -> size; i++) sum += data -> data[i];
return sum / data -> size;
}
data_type *addData(data_type *data, int val)
{
size_t newsize = data ? data -> size + 1 : 1;
data = realloc(data, sizeof(*data) + newsize * sizeof(data -> data[0]));
if(data)
{
data -> data[newsize - 1] = val;
data -> size = newsize;
}
return data;
}
int main(void)
{
data_type *data = NULL, *tmp;
int val = 0;
while(1)
{
printf("Enter number: ");
while(scanf("%d", &val) != 1);
if(val == -1) break;
printf("\n");
tmp = addData(data, val);
if(tmp) data = tmp;
else { /* add some error handling*/}
printf("Numbers above average %zu\n", countAbove(data, getAverage(data)));
}
free(data);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.