printf在新的线角色之后无法正常工作
我试图用 C 语言制作一个 AYAYA 金字塔程序,只是因为我注意到“A”和“Y”非常适合在一起,而且“A”也可以是金字塔的顶部。 该程序可以工作,但后来我想在金字塔之前创建一个对该程序的小介绍,但是通过在 printf 中放置 '\n' ,它会使 printf 中的下一个 %s 打印出一些奇怪的东西,如果我按以下方式打印每个字符一个它不这样做,这是更好解释的代码。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int base;
if (argc != 2 || (base = atoi(argv[1])) % 2 == 0) {
printf("Usage: %s n_odd_base\n", argv[0]);
return 1;
}
printf("this \\n infects next string output -->\n");
int i, j;
char spaces[base/2];
for (i = 0; i < base/2; i++) {
spaces[i] = ' ';
}
for (j = 0; j < base; j += 2) {
printf("%s", spaces);
for (i = 0; i <= j; ++i)
if (i % 2 == 0)
putchar('A');
else
putchar('Y');
printf("\n");
spaces[base/2-1-j/2] = '\0';
}
return 0;
}
这是一种输出类型,如果您尝试一下,您会发现随机字符每次都会发生变化。
fuffi@astro ayayatower]$ ./AYAYA.out 5
this \n infects next string output -->
5õLVA
AYA
AYAYA
另外,如果你有任何建议可以让这个程序更好,请告诉我,我对编程和 C 的知识很少。
[编辑]:即使没有介绍并且你输入 17 或 19,可能是其他人,但我知道这个问题也会发生这些,如果你输入131,它会正常工作,所以我不知道。
I was trying to make an AYAYA pyramid program in C just because I noticed that the 'A' and 'Y' fits really well togheter and the 'A' can also be the top of the pyramid.
The program works, but then I wanted to create a small introduction to the program before the pyramid, but by placing '\n' in the printf it makes the next %s in the printf print something strange, if i print each character one by one it doesn't do this, this is the code for better explanation.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int base;
if (argc != 2 || (base = atoi(argv[1])) % 2 == 0) {
printf("Usage: %s n_odd_base\n", argv[0]);
return 1;
}
printf("this \\n infects next string output -->\n");
int i, j;
char spaces[base/2];
for (i = 0; i < base/2; i++) {
spaces[i] = ' ';
}
for (j = 0; j < base; j += 2) {
printf("%s", spaces);
for (i = 0; i <= j; ++i)
if (i % 2 == 0)
putchar('A');
else
putchar('Y');
printf("\n");
spaces[base/2-1-j/2] = '\0';
}
return 0;
}
this a type of output, if you try it you notice that the random characters change every time.
fuffi@astro ayayatower]$ ./AYAYA.out 5
this \n infects next string output -->
5õLVA
AYA
AYAYA
Also if you have any tips to make this program better tell me please, I have very little knowledge with programming and C.
[EDIT]: that problem happens even if there is no introduction and you input 17 or 19, probably others but I know these, if you input 131 it works normally so I don't know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
数组空间不包含字符串
,因此 printf 的调用
会调用未定义的行为。
您可以这样声明数组:
此外,如果基数是奇数,则
当 j = 基数 - 1 时,表达式可以在数组外部写入。
The array spaces does not contain a string
So this call of printf
invokes undefined behavior.
You could declare the array like
Also if base is an odd number then the expression
can write outside the array when j = base - 1.