2017-02-28 62 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

是的,這也是一個有效的觀點。嗯;有多個層次可以批評問題中的代碼。 –