bug^君 2018-11-05 06:14 采纳率: 25%
浏览 248

程序中的额外输出

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 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类