本题须知
A的ASCII码是65
a的ASCII码是97
编程思路
大写字母的ASCII码比小写字母的小,且两者相差32
要将大写字母转为小写字母,大写字母+32
要将小写字母转为大写字母,小写字母-32
代码展示
方法一:
通过下标对应来判断输入字母对应的大写字母或小写字母
#include<iostream>
using namespace std;
int main()
{
char character = 65;
const char* lowercase_character = "abcdefghijklmnopqrstuvwxyz";
const char* uppercase_character = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "请输入一个字母:";
cin >> character;
if (character > 64 && character < 91) {
for (int i = 0; i < 27; ++i) {
if ((short(character) + 32) == short(lowercase_character[i])) {
cout << "该大写字母对应的小写字母为" << lowercase_character[i] << endl;
}
}
}
else if (character < 123 && character > 96) {
for (int i = 0; i <= 27; ++i) {
if ((short(character) - 32) == short(uppercase_character[i])) {
cout << "该小写字母对应的大写字母为" << uppercase_character[i] << endl;
}
}
}
else {
cout << "ERROR0--未正确输入字母" << endl;
}
return 0;
}
方法二:
通过字符类型的特点来判断输入字母对应的大写字母或小写字母
#include<iostream>
using namespace std;
int main()
{
char character;
cin >> character;
if (character >= 'a' && character <= 'z') {
cout << char(character - 32) << endl;
}
else if (character >= 'A' && character <= 'Z') {
out << char(character + 32) << endl;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
char character;
cin >> character;
if (character >= 97 && character <= 122) {
cout << char(character - 32) << endl;
}
else if (character >= 65 && character <= 90) {
cout << char(character + 32) << endl;
}
return 0;
}
编程新手,如果你还有其他方法,可以评论,我会在之后进行练习