【问题标题】:Why is my code printing every number? [closed]为什么我的代码会打印每个数字? [关闭]
【发布时间】:2016-03-16 22:46:25
【问题描述】:

我编写了这段代码,它从用户那里读取 10 个整数,将它们存储在一个数组中,然后计算并打印平均值。它还应该打印数组中大于或等于平均值​​的数字。相反,我的代码会打印出数组中的每个数字。我该如何解决这个问题?

另外,如果有人对如何简化此代码有任何提示,我将不胜感激。

#include <iostream>

using namespace std;

int main()
{
    const int ENTER_NUM = 10;
    int integer[ENTER_NUM];

    cout << "Enter "<<ENTER_NUM<<" numbers: "<<endl;
    cin >> integer[0];
    cin >> integer[1];
    cin >> integer[2];
    cin >> integer[3];
    cin >> integer[4];
    cin >> integer[5];
    cin >> integer[6];
    cin >> integer[7];
    cin >> integer[8];
    cin >> integer[9];

    int sum;
    sum = integer[0]+integer[1]+integer[2]+integer[3]+integer[4]+integer[5]+integer[6]+integer[7]+integer[8]+integer[9];

    int average;
    average = sum/ENTER_NUM;

    cout<<"Average is: "<<average<<endl;

    for(int i=0; i<10; i++)
    {
            if (integer[i]>=average);
            cout<<"Number in array greater than or equal to the average: "<<integer[i]<<endl;
    }

return 0;
}

【问题讨论】:

  • 第 23 行继续为 +integer[7]+integer[8]+integer[9];
  • 旁注:您似乎已经了解循环;那么为什么要使用循环与平均值进行比较?但是在计算初始总和时手动记下所有数组元素?这就像......好吧,不是很聪明。
  • 您应该阅读std::vectorstd::accumulate 或更一般的标准库。
  • for 循环也可用于输入数据!另一个计算总和。
  • @ThomasMatthews -- 或同一个来计算总和。

标签: c++ arrays average


【解决方案1】:

在循环中的if 后面有一个虚假的;

当你总是在ifs 上使用{} 和类似的控制结构而不是依赖“一行异常”时,这个错误发生的可能性就较小。

【讨论】:

    【解决方案2】:

    if (integer[i]&gt;=average); 末尾包含一个分号,从而消除了它控制其后的打印语句的能力。调高编译器的警告级别,您会收到关于此的消息

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2020-09-30
      相关资源
      最近更新 更多