Проблема с вашим кодом в том, что sum
является локальной переменной в функции calculation
.Поэтому, когда вы возвращаетесь к основному параметру, ваша переменная уничтожается, и sum in main
по-прежнему равно 0.
Также, если вы получаете floating point values
для dimensions
, тогда вы должны использовать double для суммы тоже.
Одно из возможных решений может быть таким:
#include<stdio.h>
#include<stdlib.h>
double calculation(int o, double *a, double *b) {
int i;
double sum =0.0;
for(i=0;i<o;++i) {
printf("Components of first vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &a[i]);
}
for(i=0;i<o;++i) {
printf("Components of second vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &b[i]);
}
for(i=0;i<o;++i) {
sum += a[i] * b[i];
}
return sum;
}
int main() {
int o;
double sum =0;
printf("How many dimensions should the vectors have?\n");
scanf("%d", &o);
double *a = malloc(o * sizeof(double));
double *b = malloc(o * sizeof(double));
if(a==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
if(b==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
sum = calculation(o,a,b);
printf("The dot product is: %lf\n", sum);
free(a);
free(b);
a=NULL;
b=NULL;
return(0);
}
Или вы можете передать адрес sum
в функцию вычисления как:
#include<stdio.h>
#include<stdlib.h>
void calculation(int o, double *a, double *b,double *sum) {
int i;
for(i=0;i<o;++i) {
printf("Components of first vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &a[i]);
}
for(i=0;i<o;++i) {
printf("Components of second vector\n");
printf("Component %d: ", i+1);
scanf("%lf", &b[i]);
}
for(i=0;i<o;++i) {
*sum += a[i] * b[i];
}
}
int main() {
int o;
double sum=0;
printf("How many dimensions should the vectors have?\n");
scanf("%d", &o);
double *a = malloc(o * sizeof(double));
double *b = malloc(o * sizeof(double));
if(a==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
if(b==NULL) {
printf("Memoryallocation was not successfull!!!");
return(1);
}
calculation(o,a,b,&sum);
printf("The dot product is: %lf\n", sum);
free(a);
free(b);
a=NULL;
b=NULL;
return(0);
}