将+指定为零

时间:2015-09-27 17:19:35

标签: c

大家好我有这段代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x1,y1,x2,y2,x3,y3;
    float a,b,a2,b2,xf3,yf3,xa,ya;

    printf("please find the line1 formula: y = ax+b\n");
    printf("please input any point (x1,y1):\n");
    printf("input x1:");
    scanf("%d",&x1);
    printf("input y1:");
    scanf("%d",&y1);

    printf("please input any point (x2,y2):\n");
    printf("input x2:");
    scanf("%d",&x2);
    printf("input y2:");
    scanf("%d",&y2);

    a=(y2-y1)/(x2-x1);
    b=y1-(a*x1);
    b=(b);

    printf("this formula: y = %fx %f\n\n",a,b);
    printf("please input any point(x3,y3):\n");
    printf("input x3:");
    scanf("%d",&x3);
    printf("input y3:");
    scanf("%d",&y3);

    xf3=x3;
    yf3=y3;

    a2 = -1/a;
    b2=y3-(a2*x3);
    xa=(b2-b)/(a-a2);
    ya=a2*xa+b2;
    printf("the line2 which contains (%.3f,%.3f) perpendicular to the line1.",xf3,yf3);
    printf("please find the intersection point of line1 and line2: \n");
    printf("(%f,%f) ",xa,ya);



    return 0;
}

它有效,但打印第一行时遇到问题。 我打算把它打印成y=ax+b。如果b为正或负,那么就没有问题。但是,如果b为零则会打印(示例)y=2.000000x0.000000我需要它y=2.000000x+0.000000

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

格式字符串%+f可能适用于您的情况。否则,您只需打印一个字符b < 0 ? '-' : '+'