当我们学习编程语言时,通常需要掌握一些基本的语法和功能。在C语言中,输出九九乘法表是一个很好的练习,因为它既简单又有趣。本文将介绍如何用C语言编写代码来输出九九乘法表。

在开始之前,请确保您已经安装了C语言的开发环境,比如VS2019。

首先,我们需要明确九九乘法表的结构。九九乘法表是一个9行9列的方阵,每个元素都是两个数的乘积。我们可以使用嵌套循环来实现这个功能,本文将介绍五种形式输出九九乘法表。

方法一:左上三角形(top_left)

主体部分代码:

 for (i = 1; i <= 9; i++){for (j = 1; j <= 9; j++){if ((i + j) <= 10){printf("%d*%d=%2d ", i, j, i * j);if (j == 9){printf("\n");}}else{printf(" ");if (j == 9){printf("\n");}}}}break;

输出为:

方法二:右上三角形(top_right)

主体部分代码

 for (i = 1; i <= 9; i++){for (j = 1; j = i){printf("%d*%d=%2d ", i, j, i * j);if (j == 9){printf("\n");}}else{printf(" ");}}}break;

输出为:

方法三:左下三角形(bottom_left)

主体部分代码

for (i = 1; i <= 9; i++){for (j = 1; j = j){printf("%d*%d=%2d ", i, j, i * j);if (j == 9){printf("\n");}}else{printf(" ");if (j == 9){printf("\n");}}}}break;

输出为:

方法四:右下三角形(bottom_right)

主体部分代码

 for (i = 1; i <= 9; i++){for (j = 1; j = 10){printf("%d*%d=%2d ", i, j, i * j);if (j == 9){printf("\n");}}else{printf(" ");}}}break;

输出为:

方法五:等腰三角形(isosceles triangle)

主体部分代码

 for (i = 9; i >= 1; i--) {for (k = 0; k<= (8 - i) * 4; k++) {printf(" ");}for (j = 1; j <= i; j++)printf("%d*%d=%2d", i, j, i * j);printf("\n\n");}break;

输出为:

我们可一将这五种情况用一个switch语句链接起来具体完整代码如下:

#define _CRT_SECURE_NO_WARNINGS 1#include#include int main(){int i,j,k,a,flag = 1;while (flag){printf("please input the number:\n1--top_left\n2--top_right\n3--bottom_left\n4--bottom_right\n5--isosceles triangle\n6--exit\n");scanf("%d", &a);getchar();switch (a){case 1://左上三角;for (i = 1; i <= 9; i++){for (j = 1; j <= 9; j++){if ((i + j) <= 10){printf("%d*%d=%2d ", i, j, i * j);if (j == 9){printf("\n");}}else{printf(" ");if (j == 9){printf("\n");}}}}break;case 2://右上三角;for (i = 1; i <= 9; i++){for (j = 1; j = i){printf("%d*%d=%2d ", i, j, i * j);if (j == 9){printf("\n");}}else{printf(" ");}}}break;case 3://左下三角;for (i = 1; i <= 9; i++){for (j = 1; j = j){printf("%d*%d=%2d ", i, j, i * j);if (j == 9){printf("\n");}}else{printf(" ");if (j == 9){printf("\n");}}}}break;case 4://右下三角;for (i = 1; i <= 9; i++){for (j = 1; j = 10){printf("%d*%d=%2d ", i, j, i * j);if (j == 9){printf("\n");}}else{printf(" ");}}}break;case 5://等腰三角for (i = 9; i >= 1; i--) {for (k = 0; k<= (8 - i) * 4; k++) {printf(" ");}for (j = 1; j <= i; j++)printf("%d*%d=%2d", i, j, i * j);printf("\n\n");}break;case 6:flag = 0;break;default:printf("please control the input value between 1 and 6!!!\n");}}system("pause");// 防止运行后自动退出,需头文件stdlib.hreturn 0;}