注册 登录
编程论坛 C++教室

元老们,帮小雏鸟看一哈哪里错了

情义控灬浮云 发布于 2018-07-29 10:48, 1825 次点击
编写一个程序,程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值
#include<iostream>
#include<cctype>
#include<array>
using namespace std;
int main()
{
    array<double,60>arr;
    int i=0;
    char ch;
    double sum,average;
    for(i=0;i<60;i++)
    {
        cin>>ch;
      if(isdigit(ch))
         { arr[i]=ch;
          sum=+ch;
      }
      else
          break;
    }
    average=sum/i;
    while(i>=0)
        if(arr[i]>average)
            cout<<arr[i--]<<endl;
    cout<<average<<endl;
    return 0;
}
我输入几个数字和一个字母,她没反应
4 回复
#2
Jonny02012018-07-29 20:26
int isdigit( int ch );
Checks if the given character is a numeric character (0123456789).
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
#3
Jonny02012018-07-29 20:54
刚看太快了, 没怎么仔细看, 问题不在那个 isdigit
你的最后一个 while 写的有问题
我重新写了一下
程序代码:
#include <iostream>
#include <vector>
#include <numeric>

using namespace std;
int main(int argc, char *argv[]) {
    vector<double> arr;
    double num;
    while(cin >> num) {
        arr.push_back(num);
    }
    double average = accumulate(arr.cbegin(), arr.cend(), 0) / arr.size();
    for(auto &c : arr) {
        if(c > average) {
            cout << c << endl;
        }
    }
    cout << average << endl;
}


[此贴子已经被作者于2018-7-29 21:01编辑过]

#4
情义控灬浮云2018-07-29 21:58
回复 3楼 Jonny0201
我的while哪里错了啊  运行到那的时候 i应该是在输入末尾的,然后递减啊
#5
Jonny02012018-07-30 01:51
回复 4楼 情义控灬浮云
如果 if 没进去 i 就递增不了, 就会一直卡在这里
1