总C语言编,求一个向量在任意向量上的投影
答案:1 悬赏:10 手机版
解决时间 2021-02-15 00:23
- 提问者网友:箛茗
- 2021-02-14 14:53
总C语言编,求一个向量在任意向量上的投影
最佳答案
- 五星知识达人网友:举杯邀酒敬孤独
- 2021-02-14 15:27
//只写了二维向量的,如果多维向量,继续扩展就可以了
#include <stdio.h>
#include <math.h>
typedef struct vector{
float x;
float y;
}Vector;
float norm(Vector v){
return sqrt(v.x*v.x+v.y*v.y);
}
float dotmuti(Vector u, Vector v){
return u.x*v.y+u.y*v.x;
}
// a's project on b
Vector project(Vector a, Vector b){
Vector temp;
float c;
if (norm(b) > 0)
c = dotmuti(a,b) / norm(b) / norm(b);
else
c = 0;
temp.x = b.x * c;
temp.y = b.y * c;
return temp;
}
int main()
{
Vector a;
Vector b;
// input vector a
printf("Pls input the first vector x and y\n");
printf("x:\n");
scanf("%f",&a.x);
printf("y:\n");
scanf("%f",&a.y);
//input vector b;
printf("Pls input the second vector x and y\n");
printf("x:\n");
scanf("%f",&b.x);
printf("y:\n");
scanf("%f",&b.y);
//output the vector
printf("Vector(%f, %f)'s projection on Vector(%f, %f) is: Vector(%f, %f).\n", a.x, a.y, b.x,b.y,project(a,b).x,project(a,b).y);
}
#include <stdio.h>
#include <math.h>
typedef struct vector{
float x;
float y;
}Vector;
float norm(Vector v){
return sqrt(v.x*v.x+v.y*v.y);
}
float dotmuti(Vector u, Vector v){
return u.x*v.y+u.y*v.x;
}
// a's project on b
Vector project(Vector a, Vector b){
Vector temp;
float c;
if (norm(b) > 0)
c = dotmuti(a,b) / norm(b) / norm(b);
else
c = 0;
temp.x = b.x * c;
temp.y = b.y * c;
return temp;
}
int main()
{
Vector a;
Vector b;
// input vector a
printf("Pls input the first vector x and y\n");
printf("x:\n");
scanf("%f",&a.x);
printf("y:\n");
scanf("%f",&a.y);
//input vector b;
printf("Pls input the second vector x and y\n");
printf("x:\n");
scanf("%f",&b.x);
printf("y:\n");
scanf("%f",&b.y);
//output the vector
printf("Vector(%f, %f)'s projection on Vector(%f, %f) is: Vector(%f, %f).\n", a.x, a.y, b.x,b.y,project(a,b).x,project(a,b).y);
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯