cin输入表达式的运用(有例,有详解)

/*用户提供5个学生分数,以计算平均分,要求:用户输入的分数不是数字,则程序拒绝,并且可以继续输入数字*/
/*从上面的要求可以知道:当出现非数字的输入时,需要处理的步骤是:
1、输入不能存入整型数组
2、重置cin的输入
3、删除错误输入
4、良好的用户提示输入*/
#include<iostream>
#define  Maxsize 5
void Show_score(int a[]);
void Aver_score(int a[]);
using namespace std;
int main() {
    int score[Maxsize];
    for (int i = 0; i < Maxsize; ++i) {
        while (!(cin >> score[i])) {
            cin.clear();//核心代码块:清除输入流的错误状态标志,
            while (cin.get() != '\n') {//读取输入缓冲区中的字符,并将其从输入缓冲区中移除
                continue;
            }
            cout << "请输入数字";
        }
    }
    Show_score(score);
    Aver_score(score);
    return 0;
}

void Show_score(int a[]) {
    cout << "学生分数:";
    for (int i = 0; i < Maxsize; ++i) {
        cout << a[i] << "   ";
    }
    cout << endl;
    
}
void Aver_score(int a[]) {
    int sum = 0;
    double aver = 0.0;
    for (int i = 0; i < Maxsize; ++i) {
        sum += a[i];
    }
    aver = sum;
    aver /= Maxsize;
    cout << "学生平均分:" << aver << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值