我只需要一些家庭作业的帮助。我正在写一个程序来找到一条直线的斜率截距方程。 y = mx + b。 问题是当b为负时,它打印y = mx + -b,而不是y = mx-b。任何人都可以指出如何解决这个问题。
void get2_pt(double *x1, double *y1, double *x2, double *y2)
{
printf("Enter the x-y cordinates of the first point separated by a space =>\n");
scanf("%lf %lf", x1, y1);
printf("Enter the x-y cordinates of the second point separated by a space =>\n");
scanf("%lf %lf", x2, y2);
}
void slope_intcpt_from2_pt(double x1,
double y1,
double x2,
double y2,
double *m,
double *y_intcpt)
{
*m = (y2 - y1) / (x2 - x1);
*y_intcpt = y2 - (*m * x2);
}
void display2_pt(double x1, double y1, double x2, double y2)
{
printf("Two-point form\nm = (%0.2lf-%0.2lf) / (%0.2lf-%0.2lf)\n",
y2,
y1,
x2,
x1);
}
void display_slope_intcpt(double m, double y_intcpt)
{
printf("Entered Q4DSI\n");
printf("Slope-intercept form\ny = %0.2lfx + %0.2lf\n", m, y_intcpt);
}
int main()
{
double x1, x2, y1, y2, m, y_intcpt;
char again;
do
{
get2_pt(&x1, &y1, &x2, &y2);
slope_intcpt_from2_pt(x1, y1, x2, y2, &m, &y_intcpt);
display2_pt(x1, y1, x2, y2);
display_slope_intcpt(m, y_intcpt);
printf("Do another conversion (Y or N) =>\n");
scanf("%c", &again);
} while (again != 'N');
return 0;
}
答案 0 :(得分:1)
在打印前测试y_intcpt
的值并相应地更改print语句。例如:
void display_slope_intcpt(double m, double y_intcpt)
{
printf("Entered Q4DSI\n");
if (y_intcpt < 0)
{
printf("Slope-intercept form\ny = %0.2lfx - %0.2lf\n", m, y_intcpt * -1.0);
}
else
{
printf("Slope-intercept form\ny = %0.2lfx + %0.2lf\n", m, y_intcpt);
}
}
答案 1 :(得分:0)
尝试
printf("Slope-intercept form\ny = %0.2lfx %c %0.2lf\n", m, (y_intcpt>=0 ? '+' : ''), y_intcpt);
作为display_slope_intcpt
函数中的第二行。
或者,如果你是一个完美主义者,并希望负号位于两个空格之间,而不是在y截距旁边,你可以做类似的事情
printf("Slope-intercept form\ny = %0.2lfx %c %0.2lf\n", m, (y_intcpt>=0 ? '+' : '-'), abs(y_intcpt));
答案 2 :(得分:0)
试试这个:
printf("Slope-intercept form\ny = %0.2lfx%+0.2lf\n", m, y_intcpt);
printf
会在此处打印正确的符号。