习题9-3 平面向量加法 (15 分)
本题要求编写程序,计算两个二维平面向量的和向量。
输入格式:
输入在一行中按照“x1 y1 x2 y2”的格式给出两个二维平面向量v1=(x1,y1)和v2=(x2,y2)的分量。
输出格式:
在一行中按照(x, y)
的格式输出和向量,坐标输出小数点后一位(注意不能输出−0.0)。
输入样例:
3.5 -2.7 -13.9 8.7
输出样例:
(-10.4, 6.0)
代码如下:
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
struct erv
{
double x;
double y;
};
/*分解字符串到结构*/
void input_erv(struct erv *q)
{
int i;
double a,b;
scanf("%lf",&a);
q->x=a;
scanf("%lf",&b);
q->y=b;
}
/*计算时间*/
struct erv *calculation_erv(struct erv *p,struct erv *q,struct erv *res)
{
res->x=p->x+q->x;
res->y=p->y+q->y;
}
/*输出时间*/
void pout_erv(struct erv *q)
{
if(fabs(q->x)<0.05) q->x=fabs(q->x);
if(fabs(q->y)<0.05) q->y=fabs(q->y);
printf("(%.1lf, %.1lf)\n",q->x,q->y);
printf("\n\n");
}
/*主函数*/
int main()
{
printf("******平面向量加法******\n\n");
struct erv *v1;
if((v1=(struct erv *)malloc(sizeof(struct erv)))==NULL)
{
printf("Sorry 分配内存失败......\n");
exit(0);
}
struct erv *v2;
if((v2=(struct erv *)malloc(sizeof(struct erv)))==NULL)
{
printf("Sorry 分配内存失败......\n");
exit(0);
}
struct erv *v3;
if((v3=(struct erv *)malloc(sizeof(struct erv)))==NULL)
{
printf("Sorry 分配内存失败......\n");
exit(0);
}
printf("******给出两个二维平面向量v1 = ( x1 ,y1 )和v2 = ( x2 ,y )的分量******\n");
printf("“x1 y1 x2 y2”\n");
input_erv(v1);
input_erv(v2);
calculation_erv(v1,v2,v3);
pout_erv(v3);
system("pause");
}