三生石@ 2018-11-05 06:14 采纳率: 100%
浏览 237

程序中的额外输出

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条回答 默认 最新

  • 胖鸭 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]);
                  }
              }
      
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)