乘法表 - Visual C
问题描述:
我想显示乘法表,这将是这样的:乘法表 - Visual C
1 2 3 4 5 6 7 8
1 1x1=1
2 1x2=2 2x2=4
3 1x3=3 2x3=6 3x3=9
4 1x4=4 2x4=8 3x4=12 4x4=16
5 1x5=5 2x5=10 3x5=15 4x5=20 5x5=25
6 1x6=6 2x6=12 3x6=18 4x6=24 5x6=30 6x6=36
7 1x7=7 2x7=14 3x7=21 4x7=28 5x7=35 6x7=42 7x7=49
8 1x8=8 2x8=16 3x8=24 4x8=32 5x8=40 6x8=48 7x8=56 8x8=64
到目前为止,我有这样的事情:
#include <stdio.h>
int main()
{
int n, i;
scanf("%d", &n);
int row,col;
if(n<1 || n>9)
{
printf("input error");
return 0;
}
for (row=0; row<=n;row++){
if(row==0)
{
for(i=1; i<=n; i++)
{
printf("\t%d", i);
}
}
for(col=0; col<=row;col++)
{
if(col==0 && row>0)
printf("%d\t", row);
if(row>=1 && col!=0)
printf("%dx%d=%d\t", col, row, col*row);
}
if(row!=n)
printf("\n");
}
return 0;
}
我认为它正确地显示表,但代码看起来马虎,我相信它可以用更简洁的方式完成。有什么建议么?
答
我会通过每个显示的行&列标题的循环展开第一遍:
#include <stdio.h>
int main()
{
int n, i;
scanf("%d", &n);
int row,col;
if(n<1 || n>9)
{
printf("input error");
return 0;
}
for(i=1; i<=n; i++)
{
printf("\t%d", i);
}
printf ("\n");
for (row=1; row<=n;row++){
printf("%d\t", row);
for(col=1; col<=row;col++)
{
printf("%dx%d=%d\t", col, row, col*row);
}
if (row!=n)
printf("\n");
}
return 0;
}
答
大多数的是什么使你的代码看起来邋遢简直是不好的风格。下面是基于什么通常被认为是良好的作风和最佳实践的几个技巧:
- 打印的提示,只要你的程序是从用户
- 把所有的变量声明一起在主函数的顶部得到输入
- 使用圆括号使操作顺序清晰,使用
&&
和||
运营商 - 使错误消息明确
- 返回负值指示错误特别是当
- 在二元运算符的两侧放置空间(即“
n < 1
”,而不是“n<1
”) - 声明多个变量时,将一个空间逗号后
- 将一个空间分号后,在for循环的条件
-
通常被认为是一个很好的风格
for
以下循环:for (condition) { ... }
-
通常被认为是一个很好的风格
if
声明以下if (condition) { ... }
个
- 使用注释来解释你的代码和增加可读性
- 使用缩进显示代码分组
除此之外,你的程序也不会在最后一行(行n
后打印一个换行符)由于最后的if语句。这会导致用户的命令行提示与您的程序打印的最后一行显示在同一行上,这可能不是您想要的。
运用所有这些事情在你的代码提供了以下结果:
#include <stdio.h>
int main()
{
// all variables declared together, at the top of main
int n, i;
int row, col; // space after comma
printf("Enter multiplication table size: "); // prompt
scanf("%d", &n);
// better-style if statement
if ((n < 1) || (n > 9)) { // parenthesis make the order of operations clearer
// clearer error message, with a newline at the end
printf("Error: table size must be at least 1 and not greater than 9\n");
return -1; // return a negative value to indicate an error
}
// better-style for loop
for (row = 0; row <= n; row++) { // spaces around binary operators, space after semi-colons
// better-style if, indented also
if (row == 0) {
// better-style for, indented
for (i = 1; i <= n; i++) { // spacing
printf("\t%d", i); // indented
}
}
// better-style for
for (col = 0; col <= row; col++) { // spacing, indentation
if ((col == 0) && (row>0)) // parenthesis, spacing, indentation
printf("%d\t", row); // indentation
if ((row >= 1) && (col != 0)) // parenthesis, spacing, indentation
printf("%dx%d=%d\t", col, row, col * row); // indentation, spacing
}
// surrounding if statement removed, so a newline is printed after every row, including the last one
printf("\n");
}
return 0;
}
请注意,我主要用来注释来说明我对代码进行了修改,而你想用它来解释功能。
对于[代码评论](https://codereview.stackexchange.com/),这个问题会不会更好? – Isac