2016-04-18 177 views
0

我想從main中調用函數「isPrime」,但只要我輸入一個數字,程序就會退出。我不知道問題是什麼?如果任何人都可以看到我做錯了什麼,我會很感激。謝謝。如何從主內部調用函數

代碼:

#include <iostream> 
#include <string> 
#include <fstream> 

using namespace std; 


ofstream myfile; 
    int num; 

int main(){ 

    cout << "Please Enter a number " << endl; 
    cin >> num; 

     while (num > 3001){ 
      cout << "Your input integer should be less than 3001. Try again, or -1 to exit" << endl; 
      cin >> num; 
      if (num == -1){ 
     break; 
      } 
     } 

    bool isPrime(num); 


    //cout << "CMSC 140 CRN <your course CRN> Project 5: Prime Numbers Written by a student <YourName> Due Date : DD/MM/YYYY>" <<endl; 

} 

bool isprime(int a){ 
    myfile.open("primelist.txt"); 
    a = num; 
    int prime; 

    if (a <= 1 || (a % 2 == 0)){  // check if the number is even 
     cout << " that is not a prime number" << endl; 
     return false; 
    } 
    else if (a == 2){ 
     cout << "tht is a prime number" << endl; 
     return true; 
    } 
    else{ 
     int divisor = 3; 
     int top = a - 1; 
     while (divisor <= top) 
     { 
      if (a % divisor == 0) 
       return false; 
     } 
     divisor += 2; //check the odd divisions 
     return true; 
    } 

    for (int i = 4; i < a; i++){ 
     if (i % 2 != 0 || i % 3 != 0){ 
      myfile << "2, 3, " << i << endl; 
     } 
    } 
} 
+0

只是省略前綴'bool':'isPrime(num);' –

+0

並在使用前添加'isPrime'聲明。 (其定義也可以在之前)。 – Jarod42

回答

2

我覺得你錯過這樣的事情: 1.更換

布爾isPrime(NUM);

布爾RET = isPrime(NUM);

或者

(無效)isPrime(NUM);

  • 可以聲明功能 布爾isPrime(中間體A);主要功能之前。
  • 4
    bool isPrime(num); 
    

    老實說,我不認爲這應該編譯。最接近的匹配,在語法上雖然是一個函數聲明......實際上什麼都不做。

    因此正如評論中所述,在該聲明中省略了bool

    +3

    你忘記了另一個明顯的匹配:一個名爲'isPrime'的類型爲'bool'的變量,用'num'初始化了 –

    +0

    另外,它看起來像OP聲明瞭一個沒有駱駝情況的函數'isprime',所以有甚至沒有名稱含糊不清 –