错误 C2143:语法错误:'if'之前缺少';'

error C2143: syntax error : missing ';' before 'if'

本文关键字:错误 if C2143 语法      更新时间:2023-10-16
    #include <iostream>
    using namespace std;
    int factor(int n);
    int main()
    { 
        int f,n;
    // Get user input
        cout << "Enter an integer: ";
        cin >> n;
    // Call factorial function
        f = factor(n);
    // Output results
        cout << n << "! = " << f << endl;
        int factor (int n)
            if(n <=1)
            {
             return 1;
            }
            else
            {
             int c = n * (n-1);
             return c;
            }
     };

我收到错误 C2143:语法错误:在"if"之前缺少";"我很好奇我是否错过了一些简单的东西。我对C++相当陌生。

您正在尝试在函数main中定义函数factor。这在C++是不允许的。此外,factor的功能体需要大括号:

int factor(int n)
{
    // function body
}
int main()
{
    // function body, factor visible
}
您需要将

因子函数从主函数中取出,并将代码放入手镯中。