无法理解程序背后的逻辑

Can't understand the logic behind a program

尝试编写一个查找向量的基本 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
            }
}

让我先整理一下您的代码,使其更具可读性并更正一些错误。

#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),然后将向量的每个分量除以范数,这就是归一化。

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

通过将问题分解成更小的部分,您会轻松很多。归一化向量需要将向量的每个分量除以向量的大小。所以你需要一种计算幅度的方法。这是一件很常见的事情,所以它有自己的功能。

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