代码之家  ›  专栏  ›  技术社区  ›  Carlos

C++循环无限运行

c++
  •  0
  • Carlos  · 技术社区  · 6 年前

    void Increment(int);
    
    int main()
    {
        int count = 1;
        while(count < 10){
            cout << “ The number after “ << count; /* Function Increment adds 1 to count */
            Increment(count);
            cout << “ is “ << count << endl;
        }
        return 0;
    }
    
    void Increment (int nextNumber)
    // Increment the parameter by 1
    {
        nextNumber++;
    }
    
    4 回复  |  直到 6 年前
        1
  •  4
  •   adn.911    6 年前

    它不起作用,因为当你路过的时候 count 到函数 Increment

    void Increment (int &nextNumber)
    // Increment the parameter by 1
    {
        nextNumber++;
    }
    

    另外,我认为没有必要创建一个单独的递增函数, count++ 关于主要功能。

        2
  •  0
  •   Nhan Phan    6 年前

    调用方法后,void Increment(int)不会更改变量。必须将&添加到medhod:void Increment(int&中)。

    那么您的代码将如下所示:

    void Increment(int &);
    
    int main()
    {
        int count = 1;
        while(count < 10){
            cout << “ The number after “ << count; /* Function Increment adds 1 to count */
            Increment(count);
            cout << “ is “ << count << endl;
        }
        return 0;
    }
    
    void Increment (int & nextNumber)
    // Increment the parameter by 1
    {
        nextNumber++;
    }
    
        3
  •  0
  •   Rhnbmpl    6 年前

    增量只发生在“increment”方法中创建的对象上。在方法之外,“nextNumber”不存在,因为没有到main函数的链接。解决方法是传递“count”变量的addrress,将地址存储在“Increment”方法的指针中,然后执行操作。指针操作将影响变量“count”的内存,因为“count”的内存引用被传递给“nextNumber”

    void Increment(int*);
    
    int main()
    {
        int count = 1;
        while(count < 10){
        std::cout << " The number after " << count; /* Function Increment adds 1 to count */
        Increment(&count);
        std::cout << " is " << count << std::endl;
        }
    return 0;
    }
    
    void Increment (int *nextNumber)
    // Increment the parameter by 1
    {
        *nextNumber=*nextNumber+1;
    }
    
        4
  •  0
  •   AKV    6 年前
    #include <iostream>
    
    using namespace::std;
    
    void Increment(int*);
    int main()
    {
        int count = 1;
        while(count < 10){
            cout << "The number after "  << count << endl;
            Increment(&count);
            cout <<  "is "  << count << endl;
        }
        return 0;
    }
    
    void Increment (int *nextNumber)
    // Increment the parameter by 1
    {
        (*nextNumber)++;
    }