我正在尝试使用一个函数来打印大量字符。字符的数量取决于用户提供的整数和 for 循环。
int get_height(void);
string printsp(void);
string printhash(void);
int main(void)
{
//running function for getting height
int h = get_height();
//setting up the column numer i
for (int i = 0; i < h; i++)
{
printsp(h - 1 - i);
printhash(i + 1);
printsp(2);
printhash(i + 1);
printf("n");
}
}
//prompting for integer within parameters
int get_height(void)
{
int h;
do
{
h = get_int("Height: ");
}
//Keeping i betwwen 1 and 8 inclusive
while (h > 8 || h < 1);
return h;
}
//printing the spaces
string printsp(void)
{
printf(" ");
}
//printing the hashes
string printhash(void)
{
printf("#");
}
我一直觉得函数调用中的参数太多了。我是新手。
调用 "c" 的参数太多
您在没有参数的情况下声明printsp
和printhash
,但使用参数调用它们,这是不一致的。
你需要一个参数并使用它,并且你不使用函数返回的值,所以最好让它们void
你想要类似(最小更改(声明的东西
void printsp(int n)
void printhash(int n)
和(最小更改(定义:
//printing the spaces
void printsp(int n)
{
while (n-- > 0)
printf(" ");
}
//printing the hashes
void printhash(int n)
{
while (n-- > 0)
printf("#");
}
另外printf
只为一个字符很贵,你可以只使用putchar
,还有其他可能性可以改善打印。
所以例如:
int get_height(void);
void printsp(int n);
void printhash(int n);
int main(void)
{
//running function for getting height
int h = get_height();
//setting up the column numer i
for (int i = 0; i < h; i++)
{
printsp(h - 1 - i);
printhash(i + 1);
printsp(2);
printhash(i + 1);
putchar('n');
}
}
//prompting for integer within parameters
int get_height(void)
{
int h;
do
{
h = get_int("Height: ");
}
//Keeping i betwwen 1 and 8 inclusive
while (h > 8 || h < 1);
return h;
}
//printing the spaces
void printsp(int n)
{
while (n-- > 0)
putchar(' ');
}
//printing the hashes
void printhash(int n)
{
while (n-- > 0)
putchar('#');
}
使用这些定义,输入 5 的结果是:
pi@raspberrypi:/tmp $ ./a.out
Height: 5
# #
## ##
### ###
#### ####
##### #####
pi@raspberrypi:/tmp $
但是请注意printsp
和printhash
可以是一个独特的函数,也可以在参数中接收要打印的字符
int get_height(void);
void printch(int n, char c);
int main(void)
{
//running function for getting height
int h = get_height();
//setting up the column numer i
for (int i = 0; i < h; i++)
{
printch(h - 1 - i, ' ');
printch(i + 1, '#');
printch(2, ' ');
printch(i + 1, '#');
putchar('n');
}
}
//prompting for integer within parameters
int get_height(void)
{
int h;
do
{
h = get_int("Height: ");
}
//Keeping i betwwen 1 and 8 inclusive
while (h > 8 || h < 1);
return h;
}
//printing ch n times
void printch(int n, char ch)
{
while (n-- > 0)
putchar(ch);
}
printsp(void)
表示此函数不接受任何参数。
printhash(void)
也一样。
for (int i = 0; i < h; i++) {
printsp();
printhash();
printsp();
printhash();
printf("n");
}
将是正确的用法。
此外,你的函数(printsp
和printhash
(应该返回一个string
,而不是什么都没有!