C++代码:数组匹配
#include <bits/stdc++.h>
using namespace std;
int a[]= {61,71,11,21,32,19,27,31};
string b[]= {"Brasilia","Salvador","Sao Paulo","Rio de Janeiro",
"Juiz de Fora","Campinas","Vitoria","Belo Horizonte"
};
int main() {
int x;
cin>>x;
for(int i=0; i<8; i++) {
if(x==a[i]) {
cout<<b[i]<<endl;
return 0;
}
}
cout<<"DDD nao cadastrado"<<endl;
return 0;
}
/*
in:11
out:Sao Paulo
*/
C++代码:结构体数组
#include <bits/stdc++.h>
using namespace std;
struct City {
int ddd;
string des;
} c[8];
int main() {
c[0].ddd=61,c[0].des="Brasilia";
c[1].ddd=71,c[1].des="Salvador";
c[2].ddd=11,c[2].des="Sao Paulo";
c[3].ddd=21,c[3].des="Rio de Janeiro";
c[4].ddd=32,c[4].des="Juiz de Fora";
c[5].ddd=19,c[5].des="Campinas";
c[6].ddd=27,c[6].des="Vitoria";
c[7].ddd=31,c[7].des="Belo Horizonte";
int x;
cin>>x;
for(int i=0; i<x; i++) {
if(x==c[i].ddd) {
cout<<c[i].des<<endl;
return 0;
}
}
cout<<"DDD nao cadastrado"<<endl;
return 0;
}
/*
in:11
out:Sao Paulo
*/
C++代码:switch-case
#include <bits/stdc++.h>
using namespace std;
int main() {
int x;
cin>>x;
switch(x) {
case 61:
cout<<"Brasilia"<<endl;
break;
case 71:
cout<<"Salvador"<<endl;
break;
case 11:
cout<<"Sao Paulo"<<endl;
break;
case 21:
cout<<"Rio de Janeiro"<<endl;
break;
case 32:
cout<<"Juiz de Fora"<<endl;
break;
case 19:
cout<<"Campinas"<<endl;
break;
case 27:
cout<<"Vitoria"<<endl;
break;
case 31:
cout<<"Belo Horizonte"<<endl;
break;
default:
cout<<"DDD nao cadastrado"<<endl;
}
return 0;
}
/*
in:11
out:Sao Paulo
*/
C++代码:if-else if-else
#include <bits/stdc++.h>
using namespace std;
int main() {
int x;
cin>>x;
if(x==61) cout<<"Brasilia"<<endl;
else if(x==71) cout<<"Salvador"<<endl;
else if(x==11) cout<<"Sao Paulo"<<endl;
else if(x==21) cout<<"Rio de Janeiro"<<endl;
else if(x==32) cout<<"Juiz de Fora"<<endl;
else if(x==19) cout<<"Campinas"<<endl;
else if(x==27) cout<<"Vitoria"<<endl;
else if(x==31) cout<<"Belo Horizonte"<<endl;
else cout<<"DDD nao cadastrado"<<endl;
return 0;
}
/*
in:11
out:Sao Paulo
*/