2017-02-28 32 views
-3

试图制定一个基本的C程序来查找向量,我以为我在某处,但我已经着手停止,而不一定是在错误方面,而是在它背后的逻辑。这里是我的代码:无法理解程序背后的逻辑

#include<stdio.h> 
#include <math.h> 

int norm_vec(int *x, int n) { 

int i; 
float modul; 

for(i=0;i<n;i++;) 
    { 
     modul=++ x[i]*x[i]; 
    } 
     modul = sqrt(modul); 

     for(i=0;i<n;i++;) 
      { 
       x[i] = x[i]/modul 
      } 
} 
+0

方不能,你应该做一个矢量结构封装组件阵列,其计,而不是无谓的周围分别通过他们这样。 – Alexander

+0

'modul'以什么值开头? –

+3

'modul = ++ x [i] * x [i];'这应该是什么意思*?顺便说一句:modul没有初始化(并且至少应该是一个double)Plus:该函数不返回一个值,它应该返回一个int。 – wildplasser

回答

1

让我先分清你的代码,这样它更具可读性并纠正一些错误。

#include <stdio.h> 
#include <math.h> 

int norm_vec(int * x, int n) 
{ 
    int i; 
    // initialize it at 0 for good practice 
    // to my knowledge if you don't initialize a float, it will be 0, but let's stay safe 
    float modul = 0; 

    for (i = 0; i < n; i++) { 
     modul += x[i]*x[i]; 
    } 

    modul = sqrt(modul); 

    for (i = 0; i < n; i++) { 
     x[i] = x[i]/modul; 
    } 
} 

对我而言,你的代码似乎在数学上是正确的。你首先计算向量的范数(你称之为modul),然后你将向量的每个分量除以范数,这就是归一化的结果。

但是,你的函数应该返回一个int,但它什么都不返回。你应该决定如何处理它。它应该返回规范还是没有规定?

+3

“据我所知,如果你不初始化一个浮点数,它将是0,但我们保持安全”不是批评,只是一个FYI,本地作用域的变量不会自动初始化在C中,并尝试读取它们会产生[未定义的行为](https://en.wikipedia.org/wiki/Undefined_behavior) – George

+0

感谢您的评论,不知道这一点。 – Scrashdown

2

将问题分解成更小的部分,您将有更容易的时间。归一化矢量需要将矢量的每个分量除以矢量的幅度。所以你需要一种计算量级的方法。这是一件很常见的事情,所以它保证它自己的功能。

您也可能想要一种打印矢量的方式,以便您可以看到您的函数按照您的预期工作。我为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); 
} 
+0

为什么不用'double'来代替'sum'(而不是'int')?使用int可以限制矢量的大小,而不是使用double,并且无论如何你都会返回double。 –

+0

@JonathanLeffler好的。我觉得有一点值得怀疑的是,我们试图首先用int组件对一个向量进行归一化。 – Alexander

+0

是的,这也是一个有效的观点。嗯;有多个层次可以批评问题中的代码。 –