加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

前瞻性声明如何运作?

发布时间:2020-12-16 09:55:43 所属栏目:百科 来源:网络整理
导读:我理解在main之前声明factorial.但是,当阶乘公式出现之后,主要如何计算答案呢? #include stdio.hlong long factorial(int);int main(){ int n; long long f; printf("Enter a number and I will return you its factorial:n"); scanf_s("%d",n); if (n 0)
我理解在main之前声明factorial.但是,当阶乘公式出现之后,主要如何计算答案呢?

#include <stdio.h>

long long factorial(int);

int main()
{
    int n;
    long long f;

    printf("Enter a number and I will return you its factorial:n");
    scanf_s("%d",&n);

    if (n < 0)
        printf("No negative numbers allowed!n"); //prevent negative numbers
    else
    {
        f = factorial(n);
        printf("The factorial of %d is %ldn",n,f);
    }

    return 0;
}

long long factorial(int n)
{
    if (n == 0)
        return 1;
    else
        return (n * factorial(n - 1));
}

解决方法

But how can main calculate the answer when the factorial formula comes after it?

第一件事 – 主要不计算答案;它是你的阶乘功能,为你做到这一点.在编写程序时,我还需要了解3个步骤:

>您将代码写入文件.
>您编译文件并且编译器检查语法错误,在此阶段没有进行代码计算仅仅是词法分析.
>然后链接发生.如果收到链接器错误,则表示您的代码编译正常,但无法找到所需的某些函数或库.这发生在我们称之为链接阶段并将阻止生成可执行文件.许多编译器同时执行编译和链接阶段.

然后,当您实际运行代码时 – 那时代码的控制流在计算发生时(即在运行时)进入阶乘函数.使用Debugger查看此内容.

下图来自Compiling,Linking and Building C/C++ Applications

从Wiki:

In computer programming,a forward declaration is a declaration of an
identifier (denoting an entity such as a type,a variable,a constant,
or a function) for which the programmer has not yet given a complete
definition
….
This is particularly useful for one-pass compilers and separate
compilation. Forward declaration is used in languages that require
declaration before use; it is necessary for mutual recursion in such
languages,as it is impossible to define such functions (or data
structures) without a forward reference in one definition: one of the
functions (respectively,data structures) must be defined first. It is
also useful to allow flexible code organization,for example if one
wishes to place the main body at the top,and called functions below
it.

所以基本上主要功能根本不需要知道因子是如何工作的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读