打印直线方程 y = mx + b
在这一步中,你将学习如何使用前几步中计算出的斜率和 y 轴截距来打印完整的直线方程。我们将修改现有的 C 程序,以标准形式 y = mx + b 显示直线方程。
继续在同一个项目目录中工作:
cd ~/project
nano line_equation_final.c
编写以下 C 代码来打印直线方程:
#include <stdio.h>
float calculate_slope(float x1, float y1, float x2, float y2) {
if (x2 - x1 == 0) {
printf("斜率未定义(垂直线)\n");
return 0;
}
return (y2 - y1) / (x2 - x1);
}
float calculate_intercept(float x, float y, float slope) {
return y - (slope * x);
}
void print_line_equation(float slope, float intercept) {
printf("直线方程:y = ");
// 打印斜率系数
if (slope == 1) {
printf("x");
} else if (slope == -1) {
printf("-x");
} else if (slope!= 0) {
printf("%.2fx", slope);
}
// 打印截距
if (intercept > 0) {
printf(" + %.2f", intercept);
} else if (intercept < 0) {
printf(" - %.2f", -intercept);
}
printf("\n");
}
int main() {
float x1 = 2.0, y1 = 3.0; // 第一个点
float x2 = 5.0, y2 = 7.0; // 第二个点
float slope = calculate_slope(x1, y1, x2, y2);
float intercept = calculate_intercept(x1, y1, slope);
printf("点 1: (%.1f, %.1f)\n", x1, y1);
printf("点 2: (%.1f, %.1f)\n", x2, y2);
printf("斜率:%.2f\n", slope);
printf("Y 轴截距:%.2f\n", intercept);
print_line_equation(slope, intercept);
return 0;
}
编译并运行程序:
gcc line_equation_final.c -o line_equation_final
./line_equation_final
示例输出:
点1: (2.0, 3.0)
点2: (5.0, 7.0)
斜率: 1.33
Y轴截距: 0.33
直线方程: y = 1.33x + 0.33
下面我们来分析一下新代码:
print_line_equation() 函数处理斜率和截距的不同情况
- 它处理斜率为 1、-1 或 0 等特殊情况
- 它为截距格式化方程并加上适当的符号
- 该函数提供了直线方程的简洁、易读表示形式
这段代码演示了如何将点和斜率信息转换为标准的线性方程格式。