【发布时间】:2014-10-26 05:48:12
【问题描述】:
我需要在 C 中打印出一个如下所示的乘法表:
1 2 3 4 5 6 7 8 9 10
1 1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 9 12 15 18 21 24 27 30
4 16 20 24 28 32 36 40
5 25 30 35 40 45 50
6 36 42 48 54 60
7 49 56 63 70
8 64 72 80
9 81 90
10 100
我现在以正确格式打印数字的循环有点乏味:
printf(" 1 2 3 4 5 6 7 8 9 10\n");
for(i=1; i<=10; i++)
{
printf("%4d", i);
for (j=i; j<=10; j++)
{
result = i*j;
if (i == 2 && j == 2)
{
printf("%8d", result);
}
else if (i == 3 && j == 3)
{
printf("%12d", result);
}
else if (i == 4 && j == 4)
{
printf("%16d", result);
}
else if (i == 5 && j == 5)
{
printf("%20d", result);
}
else if (i == 6 && j == 6)
{
printf("%24d", result);
}
else if (i == 7 && j == 7)
{
printf("%28d", result);
}
else if (i == 8 && j == 8)
{
printf("%32d", result);
}
else if (i == 9 && j == 9)
{
printf("%36d", result);
}
else if (i == 10 && j == 10)
{
printf("%40d", result);
}
else
{
printf("%4d", result);
}
}
printf("\n");
}
我在想必须有一种方法可以让这更容易,以某种方式将 int 变量连接到数字的精度中,如下所示:
if (i == j)
{
printf("%(4 * i)d", result);
}
else
{
printf("%4d", result);
}
这段代码显然行不通,但是有没有办法可以实现这样的事情,这样我就可以避免当前循环中的所有 if/else 语句?
【问题讨论】:
-
点赞
printf("%*s%d", (4 * i), " ", result);查看this code我为你写的。需要学习的点是“%*s” -
我很想关闭 Is there a way to specify how many characters of a string to print out using
printf()? 的副本。认识到自己的代码很笨拙并想知道如何改进它是件好事。
标签: c