2017-03-18 95 views
-1

我正在寫一個程序,要求飛行員輸入座標。我的void函數返回一個值並且不返回到主函數。

int main() 
{ 
    plane_checker(); 
    double angle_finder(int x, int y); 
    double distance_plane(int x, int y, int z); 
    void ils_conditions(); 
} 

在我的plane_checker()功能是:

plane_checker() 
{ 
    printf("Please enter your identification code:"); 
    scanf("%s", &plane_name[0]); 

    if((plane_name[0]== 'j') || (plane_name[0]== 'f') || (plane_name[0]== 'm') || (plane_name[0]== 'J') || (plane_name[0]== 'F') || (plane_name[0]== 'M')) 
    { 
     printf("Sorry, we are not authorized to support military air vehicles.");; 
    } 
    else 
    { 
     printf("Please enter your current coordinates in x y z form:"); 
     scanf("%d %d %d", &x, &y, &z); 

     if(z < 0) 
     { 
      printf("Sorry. Invalid coordinates."); 
     } 

    } 
    return; 
} 
然後,在其他功能,如計算距離和平面

這是我的主要功能的角度以後使用這些座標

用戶輸入座標後,我期望程序返回到主功能並繼續執行其他功能。但是,當我運行程序時,我的函數返回輸入的z值並結束程序。如在這裏看到的:

Please enter your identification code:lmkng 
Please enter your current coordinates in x y z form:1 2 2 

Process returned 2 (0x2) execution time : 12.063 s 
Press any key to continue. 

這可能是什麼原因造成的?我一字一句地檢查了我的程序,但是找不到原因呢?我錯過了什麼?

非常感謝您提前!

+0

@Schwern我沒有在main中聲明它們。我之前宣佈過他們。我只是在主 – Huzo

+1

中調用它們「*我希望程序返回到主函數並繼續執行其他函數。」這些不是函數調用,它們是前向聲明。 – Schwern

回答

1

如果你不想你的函數返回任何東西它定義成這樣

void plane_checker() 
{ 
    printf("Please enter your identification code:"); 
    scanf("%s", &plane_name[0]); 

    if((plane_name[0]== 'j') || (plane_name[0]== 'f') || (plane_name[0]== 'm') || (plane_name[0]== 'J') || (plane_name[0]== 'F') || (plane_name[0]== 'M')) 
    { 
     printf("Sorry, we are not authorized to support military air vehicles.");; 
    } 
    else 
    { 
     printf("Please enter your current coordinates in x y z form:"); 
     scanf("%d %d %d", &x, &y, &z); 

     if(z < 0) 
     { 
      printf("Sorry. Invalid coordinates."); 
     } 

    } 

} 

但是你將無法操縱插入的數據在plane_checker函數之外。您應該從plane_checker()返回插入的數據或使用指針。 https://www.tutorialspoint.com/cprogramming/c_pointers.htm

+0

我試着做void plane_checker(),但它仍然返回輸入的z值。關於指針,我沒有學會他們,但會檢查出來!謝謝 – Huzo

+0

您是否刪除了退貨;從最後? – Goran

+0

哦,我沒有看到你刪除了那個。我刪除它,現在它工作!順便說一句,謝謝 – Huzo

2

打開警告(-Wall),它會告訴你,plane_checker因爲你沒有在它有一個隱含的int返回值聲明中指定它。

test.c:1:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int] 
plane_checker() 
^ 

您還會收到許多關於未聲明的變量的警告和錯誤:x,y,z和plane_name。修復它們。如果他們是全局變量,他們不應該是。


「我希望該程序返回到主功能,並繼續與其他功能。」

這些不是函數調用,它們是函數的前向聲明。函數調用將像angle_finder(x, y)

我很抱歉地說你的代碼加載了錯誤。我建議你退後一步,讀編程一些材料C.

+0

是的,我是初學者級別的編碼員。據我瞭解,當我在我的主函數中調用函數時,我不應該聲明它是什麼類型的函數? – Huzo

+0

@Huzo再說一遍,你的代碼有可能出錯,我建議你退後一步,通過一個教程。我發現[Learn C The Hard Way](https://learncodethehardway.org/c/)非常好,但是我已經有了一些C語言經驗和編程經驗。 [TutorialsPoint上的C教程](https://www.tutorialspoint.com/cprogramming/index.htm)可能會有所幫助。 – Schwern

+1

@Huzo函數聲明在函數之外(最好在頭文件中)。函數調用是你在'main'中需要的。 –