\t 和 \n 分别是制表符和换行符转义序列,所以改变
printf("%d\t", c);
到
printf("%d", c);
摆脱标签,并删除
printf("\n");
大家齐心协力,放松新线...简单
顺便说一句:你为什么要宣布第二个int c?您的代码以声明一堆 int 开头,其中一些您不使用:
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;
如果您想要避免打印的唯一内容是 last \n(和 \t),您可以更改:
printf("\n");
与
if (i < x-1) printf("\n");
这将打印 \n 每次,除了你的循环运行的 last 时间。仅仅因为循环运行的条件是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