c - 在 main 之外定义函数

标签 c

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

main()
{
     float i;
     float x,N,sum;
     printf("enter x and N respectively");
     scanf ("%f %f", &x, &N);

     sum = 0;
     for (i=1;i<=N;i++){
          sum = sum + ((pow(x,i))/(fact(i)));
     }
     printf ("%f", sum);
}

int fact(int n){
     int i,temp;
     temp = 1;
     for (i=1;i<=n;i++){
          temp = temp*i;
          return temp;
     }

}

这是相应地打印各项的总和。我尝试在 main 内部定义事实,但有一些控制流警告,这次我在外部尝试了相同的操作,但答案错误。有什么帮助吗?

最佳答案

您不能(C99 或 C11 标准禁止您)在另一个函数(例如 main)中定义一个函数(例如 fact)。

但是,某些 C 编译器,特别是 GCC接受作为扩展以获得 nested functions .

(我不建议使用该扩展,特别是如果您是 C 新手)

当然你最好声明

int fact(int n);

您的main之前,并将其定义保留在之后。

您的代码是错误的(特别是,最好将 define mainint main(int argc, char**argv) 然后学习关于 getopt 并使用它)。使用所有警告和调试信息(例如,gcc -Wall -Wextra -g homework.c -o binaryprog...)编译它,然后使用调试器(例如,gdb ./binaryprog >)

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

相关文章:

c - 旋转窗口的工具,如 cvmovewindow

c - 用于分布式内存集群的 OpenMP 或 MPI 或 OpenMPI?

c++ - 使用 c-preprocessor 自动生成函数转发器

c++ - 我需要做什么才能将我的桌面应用程序提交到 Windows 应用商店?

c++ - 如何检测包含 header 的位置

c - 如何用表格制作 "global variable"?

c++ - 长格式和多格式路径操作库?

c - 链接到在 Cygwin 上使用 mingw 构建的库

c - 如何检测特定页面是否映射到内存中?

c++ - 由于多个 'main',STM8上的cpputest失败