I've been trying to create a program that prints a number in an array if the average of the subsequent numbers is less than the number.
Here's the code I wrote
#include <stdio.h>
int main(void) {
int a,b[100],i,m,av=0,kk,p=0,q;
scanf("%d",&a);
for(i=0;i<a;i++)
{
scanf("%d",&b[i]);
}
for(i=0;i<a;i++)
{
kk=b[i];
for(m=i+1;m<a;m++)
{
av=av+b[m];
p=p+1;
}
q=av/p;
if(kk>q)
{
printf("%d\n",kk);
}
}
}
The input I took was 7 - Number of elements
(now for the elements)
23
34
12
21
14
26
33
The output should be 34 and 33 but it is also showing 26 in the output. I've been trying to find the mistake but hitting a dead end. Help is appreciated. Thank you
转载于:https://stackoverflow.com/questions/53149219/extra-output-in-program
**
**
when i is pointing to the last element m is checking for (i+1)th element that do not exist so make the loop till last but 1 element.
for each element after checking the average, make the av and p values 0. at last print the last element which is always true
#include<stdio.h>
int main(void) {
int a,b[100],i,m,av=0,kk,p=0,q=0;
scanf("%d",&a);
for(i=0;i<a;i++)
{
scanf("%d",&b[i]);
}
for(i=0;i<a-1;i++)
{
kk=b[i];
av=0;
p=0;
for(m=i+1;m<a;m++)
{
av +=b[m];
p +=1;
}
q = av/p;
if(kk>q)
{
printf("%d ",kk);
}
}
if(i==a-1)
{
printf("%d ",b[a-1]);
}
}