derek5. 2018-11-05 06:14 采纳率: 100%
浏览 227

程序中的额外输出

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

  • 写回答

1条回答 默认 最新

  • 7*4 2018-11-05 06:37
    关注

    **

    There are two mistakes you have made

    **

    1. 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.

    2. 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]);
                  }
              }
      
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算