Cout改变变量值

时间:2014-07-09 05:29:09

标签: c++

在main函数中,如果我调用cout << answer << "\n";, 最后的答案将会改变。有人向我解释为什么会发生这种情况?

#include <iostream>

    using namespace std;

int Even(int *num){

    return (*num)/2;
}


int Odd(int *num){

    return 3*(*num)+1;
}

int Cycle (int num){
        int cycle;

        while (num != 1){

        if( num%2 == 0 ){  

            num= Even(&num) ;

        }else{

            num = Odd(&num) ;
        }

        cycle++;
    }
        return  cycle+1 ;
}



int main(){

    int num1,num2,max=0,answer;

    cin>>num1;
    cin>>num2;

    for(int i = (num1 < num2 ?  num1 : num2) ; i<=num2 ; i++ ){

        answer = Cycle(i);

//Here is the PROBLEM
        cout << answer << "\n";

        if(max < answer){
            max = answer;
        }

    }

    cout <<"Final Answer "<< max <<"\n" ;

  return 0;
}

输入1 10

没有cout的输出最终答案68 输出与cout最终答案20

1 个答案:

答案 0 :(得分:1)

问题不在于cout

首先,您的OddEven函数不应该使用指针,因为您已经返回了值。

其次,您未在cycle函数中初始化变量Cycle

此代码正确运行:

#include <iostream>
using namespace std;

int Even(int num){

    return (num)/2;
}


int Odd(int num){

    return (3*(num)+1);
}

int Cycle (int num){
    int cycle = 0;

    while (num != 1){

        if( num%2 == 0 ){

            num= Even(num) ;

        }else{

            num = Odd(num) ;
        }

        cycle++;
    }
    return  (cycle+1) ;
}



int main(){

    int num1,num2, max=0, answer;
    cin>>num1;
    cin>>num2;
    for(int i = (num1 < num2 ?  num1 : num2) ; i<=num2 ; i++ ){

        answer = Cycle(i);

        if(max < answer){
            max = answer;
        }

    }

    cout <<"Final Answer "<< max <<"\n" ;

    return 0;
}