2012-04-08 165 views
0
#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:語法錯誤:缺少';'之前'如果' 我很好奇,如果我錯過了簡單的東西。我對C++相當陌生。錯誤C2143:語法錯誤:缺少';' 'if'

+2

每當您收到一條您不明白的語法錯誤消息時,首先要做的就是開始刪除(或註釋掉)代碼,直到消息消失。 – 2012-04-08 12:45:51

+0

函數'main()'中定義了函數'int factor(int n)',您應該在外部定義它。 – Aziz 2012-04-08 12:46:50

+3

在'main'之前定義'factor',並將其稱爲'factorial'。 – 2012-04-08 12:47:26

回答

3

您正試圖在功能main內定義功能factor。這在C++中是不允許的。此外,函數體factor需要括號:

int factor(int n) 
{ 
    // function body 
} 

int main() 
{ 
    // function body, factor visible 
} 
+0

謝謝,我感謝幫助! – MIkey27 2012-04-08 15:01:02

+2

@ MIkey27:如果這解決了問題,請點擊答案旁邊的複選標記。 – 2012-04-08 16:29:19

0

你需要獲得因子函數出來的主要功能,並把裏面的代碼手鐲。