如何解决如何在C语言中使用for循环打印符号n次?
是否可以在C语言中使用n
循环来打印'#'for
次?
我曾经在Python中print(n * '#')
习惯过。
在C语言中有等同的语言吗?
for(i=0; i < h; i++) {
printf("%s\n",i * h);
}
解决方法
不。标准C中的任何机制都不可能实现。如果您希望某个子字符串的字符串重复n次,则必须自己构造它。
简单的例子:
const char *substring = "foo";
// We could use `sizeof` rather than `strlen` because it's
// a static string,but this is more general.
char buf[8192];
size_t len = strlen(substring);
char *ptr = buf;
// Ideally you should check whether there's still room in the buffer.
for (int i = 0; i < 10; ++i) {
memcpy(ptr,substring,len);
ptr += len;
}
*ptr = '\0';
printf("%s\n",buf);
,
要在for循环中输出符号'#'
n
次,则无需动态创建字符串。这样会效率低下。
只需像使用标准功能putchar
for ( int i = 0; i < n; i++ )
{
putchar( '#' );
}
putchar( '\n' );
这是一个演示程序。
#include <stdio.h>
int main(void)
{
const char c = '#';
while ( 1 )
{
printf( "Enter a non-negative number (0 - exit): " );
unsigned int n;
if ( scanf( "%u",&n ) != 1 || n == 0 ) break;
putchar( '\n' );
for ( unsigned int i = 0; i < n; i++ )
{
for ( unsigned int j = 0; j < i + 1; j++ )
{
putchar( c );
}
putchar( '\n' );
}
putchar( '\n' );
}
return 0;
}
程序输出看起来像
Enter a non-negative number (0 - exit): 10
#
##
###
####
#####
######
#######
########
#########
##########
Enter a non-negative number (0 - exit): 0
如果您需要在文件流中发送符号,请使用功能
int fputc(int c,FILE *stream);
代替putchar
。
是的,使用%.*s
格式说明符。
int h = 10; //upper limit
char pat[h*h];
memset(pat,'#',sizeof pat);
for (int i=0;i<h;i++)
{
printf("%.*s\n",i*h,pat);
}
输出:
##########
####################
##############################
########################################
##################################################
############################################################
######################################################################
################################################################################
##########################################################################################
如果我误解了你的问题,请原谅。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。