2017-02-21 34 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; 
        } 
    } 
    
    相关问题