我是C的新手,想要打印数组的一些特殊元素。
//Partial code here
char aaa[18] ;
int i = 0;
while(i < 18) {
aaa[i] = '#' ;
printf("%c", aaa[i]) ;
i = i + 4 ;
}
它应该打印4 #
aaa [0],aaa [4],aaa [8],aaa [12],aaa [16]。但事实并非如此。它将它们打印成#####
行。但我不想要那些。
答案 0 :(得分:4)
我假设你想最终打印一个字符串并获得这样的输出
"# # # # # "
减去报价。
你可以通过填写以空字符结尾的字符串然后printf
来完成此操作,如下所示:
// +1 for space for a null terminator
// = {0}; fills the array with 0s
char aaa[18+1] = {0};
// for loop is more idiomatic for looping over an array of known size
for (int i = 0; i < 18; i += 4) {
// if the remainder of dividing i by 4 is equal to 0
if (i % 4 == 0) {
// then put a '#' character in the array at aaa[i]
aaa[i] = '#';
} else {
// otherwise put a ' ' character in the array at aaa[i]
aaa[i] = ' ';
}
}
printf("%s", aaa);
答案 1 :(得分:3)
当您在每个循环中为i变量添加4时,您将连续打印阵列的位置0,4,8,12,16。
如果你想用#作为4 * nth元素打印矢量,你应该做类似的事情:
while( i < 18 )
{
if( i % 4 == 0 )
{
aaa[i] = '#';
printf("%c" ,aaa[i]);
}
else
printf(" "); // Assuming you want a space in between prints
i++;
}