21xrx.com
2025-03-19 12:31:34 Wednesday
文章检索 我的文章 写文章
C++教程:输入一组数并求平均分,统计正负数
2023-07-07 20:26:24 深夜i     --     --
C++教程 求平均分 正负数统计

C++是一种面向对象的编程语言,在计算机科学中得到了广泛的应用,它有许多重要的特性,包括高效、安全和可移植性。

在C++语言中,输入一组数并求平均分和统计正负数是基本的程序,下面我们来简单介绍如何实现。

第一步是要求用户输入一组数,可以使用循环语句实现。如:

int n, x, positive = 0, negative = 0;
float sum = 0;
cout << "请输入要计算的数的个数:";
cin >> n;
for (int i = 0; i < n; i++)
{
  cout << "请输入第" << i + 1 << "个数:";
  cin >> x;

接下来,我们需要累加输入的数,并统计正负数的个数。对于正负数的判断,可以使用判断语句实现。如:

if (x > 0)
  {
    positive++;
  }
  else if (x < 0)
  {
    negative++;
  }
  sum += x;
}

最后,我们可以计算平均分并输出结果。如:

float average = sum / n;
cout << "平均分为:" << average << endl;
cout << "正数个数为:" << positive << endl;
cout << "负数个数为:" << negative << endl;

完整程序如下:

#include <iostream>
using namespace std;
int main()
{
  int n, x, positive = 0, negative = 0;
  float sum = 0;
  cout << "请输入要计算的数的个数:";
  cin >> n;
  for (int i = 0; i < n; i++)
  {
    cout << "请输入第" << i + 1 << "个数:";
    cin >> x;
    if (x > 0)
    {
      positive++;
    }
    else if (x < 0)
    {
      negative++;
    }
    sum += x;
  }
  float average = sum / n;
  cout << "平均分为:" << average << endl;
  cout << "正数个数为:" << positive << endl;
  cout << "负数个数为:" << negative << endl;
  return 0;
}

通过这个简单的例子,我们可以了解C++实现输入一组数并求平均分、统计正负数的方法。在实际应用中,我们可以根据需求做出不同的改变,实现更多的功能。

  
  

评论区