如何编译c&c++程序?

Ros*_*han 3 c c++

我在某处读到我需要安装“构建基本打包程序”,所以我尝试了:

sudo apt-get install build-essential 
Reading package lists... Done
Building dependency tree       
Reading state information... Done
build-essential is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Run Code Online (Sandbox Code Playgroud)

但是该文件仍然无法编译或运行...

gcc -Wall -W -Werror factorial.cpp -o factorial.
Run Code Online (Sandbox Code Playgroud)

给我:

gcc -Wall -W -Werror factorial.cpp -o factorial.
factorial.cpp:3:22: fatal error: iostream.h: No such file or directory
compilation terminated
Run Code Online (Sandbox Code Playgroud)

这是我的一段代码://WAP 演示用于计算阶乘的静态成员

    #include<iostream.h>    
    #include<conio.h>
class fact
{
int i;
    static int count;
    public : 
    void calculate()
    {
        long int fact1=1;
        count++;
        for(i=0;i<=count;i++)
        {
            fact1=fact1*i;
        }
        cout<<"\nFactorial of"<<count<<"="<<fact1<<"\n";
    }
};
int fact :: count;
void main()
{
    int i;
    clrscr();
    fact f;
    for(i=1;i<=15;i++)
    {
        f.calculate();
    }
    getch();
}
Run Code Online (Sandbox Code Playgroud)

我该怎么办..???

fos*_*dom 5

您的测试源包有几个问题。

我的猜测是您正在尝试使用稍旧的 C++ 标准(gcc而不是g++)进行编译,并且可能基于 Windows 例程(使用conio)。

我已经为你整理了测试程序:

#include <iostream> /* dont need .h */    
using namespace std; /* use a namespace */
/* #include <conio.h>   this is a windows header - dont need */

class fact
{
int i;
    static int count;
    public : 
    void calculate()
    {
        long int fact1=1;
        count++;
        for (i = 2; i <= count; i++)
        {
            fact1 *= i;
        }
        cout << "\nFactorial of " << count << '=' << fact1 << '\n';
    }
};
int fact :: count;

int main(void) /* you had an invalid main declaration */
{
    int i;
    /* clrscr();  not necessary */
    fact f;
    for (i = 1; i <= 15; i++)
    {
        f.calculate();
    }
    /* getch(); not necessary */

    return 0; /* need to return a standard value */
}
Run Code Online (Sandbox Code Playgroud)

然后编译使用

g++ factorial.cpp -o factorial
Run Code Online (Sandbox Code Playgroud)

  • 计算循环也需要从 i=1 开始,否则结果将始终为 0。 (2认同)
  • 很好的评论 - 这个源有很多问题 - 效率非常低等。我回答的主要目的只是让这个东西编译! (2认同)