2017-02-21 33 views
0

所以...這是我第一次搞亂函數,幾乎從來沒有與for工作,我想創建一個打印你好的函數與參數(n)所說的次數一樣多。功能和for循環:第一次弄亂它,現在它只是一個爛

#include <iostream> 
int say_hello(int n){ 
    for(int n, int t=0; t!=n; t++){ 
     std::cout << "Hello" << std::endl; 
    } 
} 


int main(){ 
    say_hello(5); 
    return 0; 
} 

但我似乎已經做了一些可怕的錯誤,因爲所有這些錯誤。之前預期不合格的ID 'INT'

  • 錯誤:

    • 錯誤預期 ';'在'int'之前
    • 警告:對於增量表達式沒有影響[-Wunused-value]
    • 錯誤:預計')'之前';'代幣
    • 錯誤:'t'未在此範圍內聲明
    • 錯誤:預計';'之前「)」標記
    • 警告:在函數沒有返回語句,返回非void [-Wreturn型]

    我想學習C++正確和至少試着進不了太多的壞習慣,任何關於網站的建議或初學者挑戰?

  • +3

    前cluelessly潛入語言讀一本好書,如「C++入門第5版」。它會教你所有的基礎知識 –

    +5

    編譯 - 看看第一個錯誤 - 解決這個問題。重複 –

    +0

    我知道我可以使用「while」循環,但我也想學習「for」。 – Macronical

    回答

    4

    你的問題歸結爲與

    for(int t=0; t!=n; t++){

    更換

    for(int n, int t=0; t!=n; t++){

    你不需要重新聲明n(因爲它是一個功能參數),這也修復for循環中的語法錯誤。該語法錯誤是所有編譯器診斷的原因。通常情況下,第一個編譯器診斷是你應該關注的。

    此外,不要忘記從say_hello返回一個值,或將其設置爲void返回類型。

    +0

    感謝讓現在更有意義 – Macronical

    +1

    您必須將't!= n'改爲't Mischo5500

    +0

    @ Mischo5500:好地方,也在問題規範中。考慮將其置於答案中。 – Bathsheba

    2

    函數中有一個輸入錯誤。您不應在隱藏該參數的for語句中聲明變量n

    int say_hello(int n){ 
        for(int n, int t=0; t!=n; t++){ 
         ^^^^^^ 
        std::cout << "Hello" << std::endl; 
        } 
    } 
    

    另外t對循環中的索引不是很好的名稱。最好使用例如名稱i

    此外,函數是不安全的,因爲傳遞給函數的參數可能是負數。

    該函數雖然返回類型爲int,但它不返回任何內容。因此該函數具有未定義的行爲。

    所以更正確的函數定義可以像

    void say_hello(unsigned int n) 
    { 
        for (unsigned int i = 0; i != n; i++) 
        { 
         std::cout << "Hello" << std::endl; 
        } 
    } 
    

    或者也可以到將允許鏈條與其他功能的功能流返回參考。

    例如

    std::ostream & say_hello(unsigned int n, std::ostream &os = std::cout) 
    { 
        for (unsigned int i = 0; i != n; i++) 
        { 
         os << "Hello" << std::endl; 
        } 
    
        return os; 
    } 
    

    事實上局部變量i中的身體for語句不使用。所以它可以被刪除。在這種情況下,您可以使用while循環而不是for循環。例如

    std::ostream & say_hello(unsigned int n, std::ostream &os = std::cout) 
    { 
        while (n--) 
        { 
         os << "Hello" << std::endl; 
        } 
    
        return os; 
    } 
    
    +0

    while可能是for循環:'for(; n> 0; - n)' – Caleth

    0

    您可以糾正你for聲明是這樣的:

    // n cannot be negative since we are counting from 0 
    // hence we have an unsigned int argument 
    int say_hello(unsigned int n) { 
        for(unsigned int t=0; t<n; t++) { // t ranges from 0 to n-1 i.e. loop executes n times 
         std::cout << "Hello" << std::endl; 
        } 
    } 
    
    相關問題