gpt4 book ai didi

c - 删除c程序中的制表符/空格

转载 作者:行者123 更新时间:2023-11-30 18:31:48 29 4
gpt4 key购买 nike

我试图阻止在每行输出的末尾打印尾随选项卡。我怎样才能做到这一点?

其余代码可以按照我的需要工作

#include <stdio.h>
int main()
{
int i, j, k, y, z, x, c, b, a, C;
scanf("%d", &x);

for(i=0; i<x; i++){
for(j=0; j<x; j++){
int c = 0;
for(k=0; k<x; k++){

y = (i+1)*(k+1);
z = (j+k);
c = (z*y)+c;
}
printf("%d\t", c);
}
printf("\n");
}
}

最佳答案

\t\n分别是制表符和换行符转义序列,因此更改

printf("%d\t", c);

printf("%d", c);

摆脱标签,并删除

printf("\n");

一起,松开新的线条......很容易
顺便说一句:你为​​什么要声明第二个int c ?您的代码首先声明一堆整数,其中一些您不使用:

int i, j, k, y, z, x, c, b, a, C;
//last 3 aren't used
//c declared here, though
//I'd write:
int i, j, k, y, z, x, c;

再往下:

//inside second loop:
int c = 0;
//would be better if wou wrote:
c = 0;

最后的注释:您缺少 return声明,但是你的main函数的签名表明(正确地)主函数应该返回 int,而不是 void。
添加return 0;在最后

如果您唯一想避免打印的是最后\n(和\t),您可以更改:

printf("\n");

if (i < x-1) printf("\n");

每次都会打印\n,除了循环运行的最后时间。很简单,因为循环运行的条件是 i<x ,打印换行符的条件是i<x-1 .
就您的选项卡而言,替换:

 printf("%d\t", c);

与:

if (j < x - 1) printf("%d\t", c);
else printf("%d", c);

正是您所需要的。
也就是说,从x开始是一个常量值,最好分配 x-1到那些未使用但已声明的整数之一:

scanf("%d", &x);
a = x -1;

然后,由于您正在使用以下代码检查何时打印一行的最后一个数字:

if (j < a) printf("%d\t", c);//replaced x - 1 with a here
else printf("%d", c);

您可以放心地假设else子句仅适用于每行的最后一个数字,那么为什么不在那里添加换行符呢?

if (j < a) printf("%d\t", c);//replaced x - 1 with a here
else printf("%d\n", c);

总的来说,这将为您留下以下代码:

#include <stdio.h>
int main()
{
int i, j, k, y, z, x, c, a;
scanf("%d", &x);
a = x - 1;
i = 0;
for(i=0; i<x; i++){
for(j=0; j<x; j++){
c = 0;
for(k=0; k<x; k++){
y = (i+1)*(k+1);
z = (j+k);
c = (z*y)+c;
}
if (j < a) printf("%d\t", c);
else printf("%d\n", c);
}
}
return 0;//ADD A RETURN STATEMENT!!
}

这仍然在最后一行输出之后添加一个新行。要删除它,也只需编写:

if (j < a) printf("%d\t", c);
else if (i < a) printf("%d\n", c);//check if we're in the last i-loop
else printf("%d", c);//if so, don't print new line

工作完成...我已经尝试过此代码 and you can see the output on this codepad

关于c - 删除c程序中的制表符/空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19978601/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com