c - 从 main 之外的函数打印 double

标签 c printf double function-prototypes

我是 c 语言新手,尝试使用主函数之外的函数,我想测试我得到的结果,但在打印函数中的值时发现错误。

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

/*function prototype f*/
int f(double x);

/*main*/
int main(void){

   double x = 0.1;

   printf("the value is %.3f\n", f(x)); 
   printf("the value is %.3f", sqrt(1.0-(x*x))); 

   return 0;
}

int f(double x){
    double value;
    value = sqrt(1.0-(x*x));}
    return value;
}

这段基本代码从给定的 x 中查找一个值,我稍后想在循环中使用该值。当我运行这个但是我得到以下输出

the value is -1.....
the value is 0.995

(…是一个随机序列 字符)

我不确定函数 f 和主函数内计算的实际值有什么区别以及为什么我会遇到这个问题

最佳答案

您在原型(prototype)中使用了 int 而不是 double 。这应该会给你正确的答案。

#include <stdio.h>
#include <math.h>
#include <conio.h>

/*function prototype f*/
double f(double x);

/*main*/
int main() {

    double x = 0.1;

    printf("the value is %.3f\n", f(x));
    printf("the value is %.3f", sqrt(1.0 - (x*x)));

    _getch();
    return 0;
}

double f(double x) {
    double value;
    value = sqrt(1.0 - (x*x));
    return value;
}

关于c - 从 main 之外的函数打印 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53547085/

相关文章:

c - 在 sscanf 中指定可变字段宽度

c++ - C++ 中的异常处理 : Throwing a double when using "throw(int)"

javascript - React.PropTypes.number 随最小值和最大值 float

c - 在 C/C++ 中传递和修改多维数组

c++ - 我可以在 Microsoft C++ 中测量 sprintf 所需的缓冲区吗?

c - 通过 MAC 地址验证 TCP 连接来自同一台机器

c - 在c中将整数写入文件

Java 精确计算 - 使用选项

c - 固定大小数组的动态数组

c - Linux网络编程。 "read([...])"幕后发生了什么?