下面是边界阶段方法的代码,该方法返回极限的中点。但是它没有将值返回给main()函数。 注释出现问题的行。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float func(float x)
{
float f = (pow(x,2) + (54 / x));
return f;
}
float bPhase(float x0, float delta)
{
float x1 , f0, f1, f2, a, b, mPt;
int k, p;
k = 0;
p = 0;
f0 = func(x0 - delta);
p++;
f1 = func(x0);
p++;
f2 = func(x0 + delta);
p++;
if(f0 <= f1 && f1 <= f2)
delta = -1 * delta;
else
delta = delta;
printf("%f %f %f\n", f0, f1, f2);
x1 = x0 + pow(2,k) * delta;
while(func(x1) < func(x0))
{
k++;
a = x0;
x0 = x1;
x1 = x1 + pow(2,k) * delta;
b = x1;
printf("%f %f %f\n", func(a),func(x0),func(b));
p++;
}
printf("Minimum lies between %.3f and %.3f", a, b);
printf("\nIteration no: %d\n", k+1);
printf("Total no. of function evaluations: %d\n", p);
mPt = ((a+b)/2.0);
printf("%f\n", mPt); //Here prints 5.1
return mPt; //Should return 5.1, but not returning
}
int main(void)
{
float x0, mPt;
float delta;
printf("Enter initial guess: "); // guess is .6
scanf("%f", &x0);
printf("Enter increment: "); // 0.5
scanf("%f", &delta);
bPhase(x0, delta);
printf("\n%f\n", mPt); //should print 5.1 but prints random
return 0;
}
函数bPhase不返回任何东西。请帮忙。主函数未从bPhase函数接收mPt的值。 一个新手。谢谢。
答案 0 :(得分:3)
您在main
中有一个名为mPt
的变量,在bPhase
中有一个名为mPt
的变量。这些不是相同的变量。在不同的范围内,不同的变量可能具有相同的名称。
此外,当bPhase
返回时,您不对返回值做任何事情。您需要将其分配给mPt
。然后,您将看到期望的值。
mPt = bPhase(x0, delta);
答案 1 :(得分:1)
您的#ifndef _ZZIP_ZZIP_H /* zziplib.h */
#define _ZZIP_ZZIP_H
#include <zzip/types.h>
#ifdef __cplusplus
extern "C" {
#endif
//Code
#ifdef __cplusplus
}
#endif
#endif /* _ZZIPLIB_H */
函数中有一个名为#include "../zziplib-13.69/zzip/zzip.h"
#include "../zziplib-13.69/zzip/lib.h"
的变量,但是没有为它分配从mPt
返回的值,因此该变量未初始化。
执行此操作:
main
我还会读到C的scope rules,因为我得到的印象是,您认为bPhase
中的变量 mPt = bPhase(x0, delta);
与{中的变量mPt
相同{1}}。