-这道题其实也是一道简单题,我主要还是用其来学习C++,通过这道题,了解到了c++中的字符和int之间的转换,首先贴上代码吧
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
int n;
cin >> n;
string s[n];
vector<string > err;//保存错误的号码
for(int i=0;i<n;i++){
cin >> s[i];
}
int count = 0;
int w[17] = {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};//权重
char m[17] = {'1','0','X','9','8','7','6','5','4','3','2'};//校验码
for(int i=0;i<n;i++){
int sum = 0;
for(int j=0;j<s[i].length()-1;j++){
sum += (s[i][j] - '0') * w[j];//这边就是字符转换成int
}
int z = sum % 11;
if(m[z] != s[i][s[i].length()-1]){
count++;
err.push_back(s[i]);
}
}
if(count == 0){
cout << "All passed";
}
for(int i=0;i<err.size();i++){
cout << err[i] << endl;
}
return 0;
}
- 我上面的字符(char)变换为int直接“ -‘0’ ”就可以了,没有必要使用atoi()和stoi()函数;
- atoi()和stoi()函数都是将字符串(string)—>int;