gpt4 book ai didi

c - matlab中c函数返回值错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:51 24 4
gpt4 key购买 nike

我想用 c 编写我的 matlab 程序的一些功能,以使其更快。但是这个函数不返回表达式的结果。它返回一些不同的值,如 29。在不调用函数的情况下(说到将表达式放在我调用函数的地方的函数内部)它就可以工作。即使在函数内部,表达式的结果也是正确的,但在 return 之后就不是了...


double distance = 0;
// function call
distance = distpos(position[0], position[1], *(origin), *(origin+1));
printf("%f", distance); // incorrect


// funktion
double distpos(double x1, double y1, double x2, double y2)
{
printf("%f", sqrt(pow((x1 - x2),2) + pow((y1 - y2),2))); // correct
return sqrt(pow((x1 - x2),2) + pow((y1 - y2),2));
}

//编辑 ------

我使用的是 Matlab 7.3.0 (R2006b)。

以下代码无效:

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

void main()
{
double position[2] = { 5, 6 };
double origin[2] = { 3, 4 };

double distance = 0;
// function call
distance = distpos(position[0], position[1], *(origin), *(origin+1));
printf("%f\n", distance); // incorrect

}

// funktion
double distpos(double x1, double y1, double x2, double y2)
{
printf("%f\n", sqrt(pow((x1 - x2),2) + pow((y1 - y2),2))); // correct
return sqrt(pow((x1 - x2),2) + pow((y1 - y2),2));
}

void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
main();
}

结果:

2.828427

639.000000

此代码确实有效:

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


// funktion
double distpos(double x1, double y1, double x2, double y2)
{
printf("%f\n", sqrt(pow((x1 - x2),2) + pow((y1 - y2),2))); // correct
return sqrt(pow((x1 - x2),2) + pow((y1 - y2),2));
}


void main()
{
double position[2] = { 5, 6 };
double origin[2] = { 3, 4 };

double distance = 0;
// function call
distance = distpos(position[0], position[1], *(origin), *(origin+1));
printf("%f\n", distance); // incorrect

}



void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
main();
}

结果:

2.828427

2.828427

这意味着:函数是在使用之前声明还是在使用之后声明的,这是有区别的。(我已经知道你应该在使用它之前声明一个函数,但你不能这样做)

最佳答案

我可以确认默认的 MEX 编译器 (Lcc-win32) 确实成功编译了代码。 @Vicky 在评论中解释了错误结果的原因...

现在以后,如果你想看到任何警告,启用详细模式:

>> mex -v a.c
...
Warning a.c: 16 missing return value
Warning a.c: 19 declaration of `distpos' does not match previous declaration at a.c 14
0 errors, 2 warnings
...

我应该提到 VS2010 和 MinGW-GCC4 都会抛出编译错误:

> gcc -o a.exe a.c
a.c:18:8: error: conflicting types for 'distpos'
a.c:13:20: note: previous implicit declaration of 'distpos' was here

> cl a.c
a.c(18) : error C2371: 'distpos' : redefinition; different basic types

一般来说,你应该总是在使用它们之前定义函数,或者使用function prototypes .

关于c - matlab中c函数返回值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7387437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com