C++统计正数数目和负数的数目,并计算平均值

来源:互联网 发布:自学c语言教程 编辑:程序博客网 时间:2024/04/25 03:19

编写一个程序,读入整数,数目未定,统计读入的正数数目和负数的数目,并计算平均值、如果读入的是0,程序终止。平均值以浮点数形式显示



#include <iostream>
using namespace std;
void main()
{
    int positiveNum = 0;
    int negativeNum = 0;
    int count = 0;
    double total = 0;
    cout<<"输入一个数字"<<endl;
    int numb;
    while (cin>>numb)
    {
        if (numb>0)
        {
            positiveNum++;
            total+=positiveNum;
        count++;
        }
        if(numb<0)
        {
            negativeNum++;
            total+=negativeNum;
          count++;
        }
        if(numb==0)break;
        cout<<"输入一个数字"<<endl;
        
    }

    cout<<"正数的数目是:"<<positiveNum<<endl;
    cout<<"负数的数目是:"<<negativeNum<<endl;
    cout<<"平均数是:"<<total/count<<endl;
}