,具體轉換規則如下:
90~100為A;
80~89為B;
70~79為C;
60~69為D;
0~59為E;
如果輸入數據不在0~100范圍內,請輸出一行:“Score is error!”。
這題的關鍵在於最后一句如果輸入數據不在范圍內如何處理?
如果簡單的定義一個整型變量,再復制,如果輸入一個字母或者一串字符就會出錯。
#include<iostream>
using namespace std;
int main()
{
int a;
while (cin>>a&&a!=EOF)
{
if (a >= 0 && a <= 59)
cout << "E" << endl;
else if (a <= 69)
cout << "D" << endl;
else if (a <= 79)
cout << "C" << endl;
else if (a <= 89)
cout << "B" << endl;
else if (a <= 100)
cout << "A" << endl;
else
cout << "Score is error!" << endl;
}
system("pause");
return 0;
}
上面這段代碼運行如何輸入字母,程序會立即結束。原因是檢測到輸入流錯誤,沒有對a賦值自然不會進while循環。
解決這個錯誤可以改為這樣。
#include<iostream>
using namespace std;
int main()
{
int a;
while (1)
{
cin >> a;
if (!cin)
{
cin.clear();
cin.sync();
cout << "Score is error!" << endl;
continue;
}
if (a<0)
cout << "Score is error!" << endl;
else if ( a <= 59)
cout << "E" << endl;
else if (a <= 69)
cout << "D" << endl;
else if (a <= 79)
cout << "C" << endl;
else if (a <= 89)
cout << "B" << endl;
else if (a <= 100)
cout << "A" << endl;
else
cout << "Score is error!" << endl;
}
system("pause");
return 0;
}
用cin.clear();來重置流,用cin.sync();來清空流。
具體解釋看另一篇隨筆。
