简体   繁体   English

函数未在C中返回正确的值

[英]Function is not returning the right value in C

I'm trying to make a program that finds the root of an equation. 我正在尝试创建一个找到方程根的程序。 Everything about my program works just fine, except for the equation itself: it keeps returning wrong values (1, infinity, 0, ...). 关于我的程序的一切工作都很好,除了方程本身:它不断返回错误的值(1,无穷大,0,...)。

This is the function I'm evaluating: 这是我正在评估的功能:

double f(x) {
    return exp(-x)-sin(M_PI*x/2.);
}

For example, f(.3) should be .287, but it returns 1.000. 例如,f(.3)应该是.287,但它返回1.000。 Weird thing is, I tried the exact same code on another computer a while ago and it worked just fine. 奇怪的是,我前一段时间在另一台计算机上尝试了完全相同的代码并且工作得很好。

double f(x) {
    return exp(-x)-sin(M_PI*x/2.);
}

The type for x is not declared, so it defaults to int . x的类型未声明,因此默认为int

You pass .3 , so it coerced to int and become 0. 你传递.3 ,所以它强制转换为int并变为0。

exp(-0)-sin(M_PI*0/2.) == exp(0)-sin(0) == 1.0-0 == 1.0

Please find yourself a better compiler, and turn on warnings. 请找到一个更好的编译器,然后打开警告。

Probably you should cast your variable. 可能您应该强制转换变量。 That usually happens to me with divisions. 这通常发生在我的师上。

double f(double x) {
 ......
}
#include <stdio.h>
#include <math.h>

double f(double x) {
    return exp(-x)-sin(M_PI*x/2.);
}

int main(void){
    printf(".3 = %f",f(.3));
    getchar();
    return 0;
}

results: '.3 = 0.286828' 结果:“。3 = 0.286828”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM