roberthsu2003 / cAndC-

48 stars 18 forks source link

老師您好:在while1_s這題有一些小BUG #3

Closed RJTseng closed 10 months ago

RJTseng commented 4 years ago

在while迴圈中應新增一項條件式 if (score >= 0) sum +=score; else times--; 原因:若輸入負數中斷迴圈時,sum會加總負數並且times會多一。

roberthsu2003 commented 4 years ago

已經解決。謝謝!

#include <iostream>
using namespace std;

int main() {
    short score=0;
    short sum = 0;
    unsigned times = 0;
    while (true){
        cout << "請輸入第" << times+1 << "位學生的成績:";
        cin >> score;
        if(score < 0)
            break;      
        sum += score;
        times++;
    }

    cout << "全班總成績為:" << sum << "平均為:" << (float)sum / times <<
    endl;
}