将问题分解成更小的部分,您将有更容易的时间。归一化矢量需要将矢量的每个分量除以矢量的幅度。所以你需要一种计算量级的方法。这是一件很常见的事情,所以它保证它自己的功能。
您也可能想要一种打印矢量的方式,以便您可以看到您的函数按照您的预期工作。我为Vector
写了一个打印功能的例子。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
typedef struct Vector {
int *components;
int arity;
} Vector;
double squaredMagnitude(Vector);
double magnitude(Vector);
void normalize(Vector);
void printVector(Vector);
double squaredMagnitude(Vector v) {
double sum = 0;
for (int i = 0; i < v.arity; i++) {
int component = v.components[i];
sum += component * component;
}
return sum;
}
double magnitude(Vector v) {
return sqrt(squaredMagnitude(v));
}
void normalize(Vector v) {
double mag = magnitude(v);
for (int i = 0; i < v.arity; i++) v.components[i] /= mag;
}
void printVector(Vector v) {
printf("{");
for (int i = 0; i < v.arity - 1; i++) printf("%i, ", v.components[i]);
if (v.arity != 0) printf("%i", v.components[v.arity - 1]);
printf("}\n");
}
int main() {
int components[] = {0, 5, 0};
int componentCount = sizeof(components)/sizeof(*components);
Vector v;
v.components = malloc(componentCount);
memcpy(v.components, components, sizeof(components));
v.arity = componentCount;
normalize(v);
printVector(v);
}
方不能,你应该做一个矢量结构封装组件阵列,其计,而不是无谓的周围分别通过他们这样。 – Alexander
'modul'以什么值开头? –
'modul = ++ x [i] * x [i];'这应该是什么意思*?顺便说一句:modul没有初始化(并且至少应该是一个double)Plus:该函数不返回一个值,它应该返回一个int。 – wildplasser