我的代码需要一些帮助。问题是:
写一个函数void printSquare(char c, int size)
接受字母表中的字母和3到10之间的数字
生成以下字母矩形:
如果传递的信件是a
且尺寸为4:
abcd
bcde
cdef
defg
如果字母为W
且大小为6,则输出应为
WXYZAB
XYZABC
YZABCD
ZABCDE
ABCDEF
BCDEFG
我一直试图调试这个很长一段时间,无法到达任何地方并需要帮助。这就是代码现在的样子:
void printSquare(char c, int size);
int main() {
printSquare('b', 4);
system("pause");
return 0;
}
void printSquare(char c, int size){
int counter = 0;
char letters[26] = { 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
for (int i = 0; i < 26; i++){
if (c == letters[i]){
int temp = i;
for (int j = 0; j < size; j++){
letters[i] = letters[temp];
temp++;
for (int k = 0; k < size; k++){
printf("%c", letters[i]);
letters[i++];
}
printf("\n");
}
}
}
}
答案 0 :(得分:4)
假设编码大写和小写字母是连续的(例如ASCII),你可以考虑这样的事情:
void printSquare(char c, int size)
{
char a = ('A' <= c && c <= 'Z') ? 'A' : 'a';
for (int i = 0; i < size; ++i)
{
for (int j = 0; j < size; ++j)
// (c - a) is the offset of c from 'A' or 'a'
// i defines an extra offset for every line, so lines start with c, c+1, ...
// j defines an offset for a character within line
// % 26 makes sure that overall offset does not go beyond the alphabet length
printf("%c", a + (c - a + i + j) % 26);
printf("\n");
}
}
答案 1 :(得分:1)
void printSquare(char c, int size){
if(isalpha(c) && 3 <= size && size <= 10){
const char *table = isupper(c) ?
"ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" :
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" ;
char *p = strchr(table, c);
for(int i = 0; i < size; ++i){
fwrite(p++, 1, size, stdout);
puts("");
}
}
}