標籤:
一、軟體要求
關於閏年(leap year)的判定,是非常簡單的。給定一個年份,若該年能被4整除,但卻不能被100整除,或者可以被400整除,則我們認定該年為閏年,否則便為平年。
對於正常的使用者,若按要求輸入任意年份,我們都能給予判定是否為閏年。但是,對於一些非法使用者,他們可能並不會按要求進行輸入。比如,可能有點使用者並不是輸入的年份,而是一些字串或非正整數,例如2012abc,-1868,2015.5等等。對於這些非法的輸入,如果我們不做相應的處理,可能將會導致程式崩潰甚至造成更大的危害。
二、測試分析
對於可能出現的情況,我做了如下分析:
| 編號 |
輸入 |
期望輸出 |
| 1 |
2012 |
2012 is leap year |
| 2 |
1900 |
1900 is nonleap year |
| 3 |
2000 |
2000 is nonleap year |
| 4 |
2015 |
2015 is nonleap year |
| 5 |
2015abc |
Input Invalid |
| 6 |
2015.5 |
Input Invalid |
| 7 |
-2015 |
Input Invalid |
三、測試代碼
#include <iostream>#include <sstream>using namespace std;void CheckLeapYear(string year){ for(int i = 0; i < year.size();i++){ if(year.at(i)>‘9‘ || year.at(i) < ‘0‘){ cout << "Input Invalid!"<< endl; return; } } stringstream ss; int num; ss << year; if(!ss.good()){ cout << "stringstream error!" << endl; } ss >> num; if((num % 4 == 0 && num % 100 != 0)|| num % 400 == 0) cout << num << " is leap year!"<< endl; else cout << num << " is nonleap year!"<< endl;}int main(){ string year; cout << "Please input a year: "; while(cin >> year){ CheckLeapYear(year); cout << "\nPlease input a year: "; } return 0;}
四、測試結果
軟體測試——閏年