心得(new,if短路原理)
new[](new的數組版)要求元素對象的類型必須具有默認構造函數(內建類型的“默認構造函數”是什么也不做),否則將不能使用new[]。
???突然發現,這道題何必用new?用vector<ID> id不是很好嗎?
題目描述
一個合法的身份證號碼由17位地區、日期編號和順序編號加1位校驗碼組成。校驗碼的計算規則如下:
首先對前17位數字加權求和,權重分配為:{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};然后將計算的和對11取模得到值Z;最后按照以下關系對應Z值與校驗碼M的值:
Z:0 1 2 3 4 5 6 7 8 9 10
M:1 0 X 9 8 7 6 5 4 3 2
現在給定一些身份證號碼,請你驗證校驗碼的有效性,并輸出有問題的號碼。
輸入描述:
輸入第一行給出正整數N(<= 100)是輸入的身份證號碼的個數。隨后N行,每行給出1個18位身份證號碼。
輸出描述:
按照輸入的順序每行輸出1個有問題的身份證號碼。這里并不檢驗前17位是否合理,只檢查前17位是否全為數字且最后1位校驗碼計算準確。如果所有號碼都正常,則輸出“All passed”。
輸入例子:
4
320124198808240056
12010X198901011234
110108196711301866
37070419881216001X
輸出例子:
12010X198901011234
110108196711301866
37070419881216001X
代碼
使用了短路原理:
92行:printCount == 0 && cout << "All passed";
相當于: if (printCount == 0)cout << "All passed";
#include<iostream>
#include<string>
using namespace std
;int WEIGHT
[] = { 7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2 };class ID
{
public
:string num
;int intNum
[18] = { -1 };bool valid
= true
;void input(string
);void checkChar();void checkNum();
};
void ID
::input(string str
)
{this
->num
= str
;
}
void ID
::checkChar()
{int i
;for (i
= 0; i
< 17; i
++){if (this
->num
[i
] < '0' || this
->num
[i
] >'9'){this
->valid
= false
;return;}this
->intNum
[i
] = this
->num
[i
] - 48;}
}
void ID
::checkNum()
{int i
;int sum
= 0;for (i
= 0; i
< 17; i
++){sum
+= this
->intNum
[i
] * WEIGHT
[i
];}sum
%= 11;switch (sum
){case 0:if (this
->num
[17] == '1')break;case 1:if (this
->num
[17] == '0')break;case 2:if (this
->num
[17] == 'X')break;case 3:if (this
->num
[17] == '9')break;case 4:if (this
->num
[17] == '8')break;case 5:if (this
->num
[17] == '7')break;case 6:if (this
->num
[17] == '6')break;case 7:if (this
->num
[17] == '5')break;case 8:if (this
->num
[17] == '4')break;case 9:if (this
->num
[17] == '3')break;case 10:if (this
->num
[17] == '2')break;default:this
->valid
= false
;}
}int main()
{int total
;cin
>> total
;ID
*pID
= new ID
[total
];int i
;string str
;for (i
= 0; i
< total
; i
++){cin
>> str
;(pID
+ i
)->input(str
);(pID
+ i
)->checkChar();if ((pID
+ i
)->valid
== false
)continue;(pID
+ i
)->checkNum();}int printCount
= 0;for (i
= 0; i
< total
; i
++){if ((pID
+ i
)->valid
== false
){cout
<< (pID
+ i
)->num
<< endl
;printCount
++;}}printCount
== 0 && cout
<< "All passed";system("pause");
}
總結
以上是生活随笔為你收集整理的牛客网_PAT乙级_1031. 查验身份证(15)【class new一个数组】的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。