[英]Cout change the variable value
In the main function,if i call the cout << answer << "\\n";
在主函数中,如果我调用
cout << answer << "\\n";
, the final answer will be change.Can someone explain to me why this happen ? ,最终的答案将是改变。有人可以向我解释为什么会这样吗?
#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;
}
Input 1 10 输入1 10
Output without cout Final Answer 68 Output with cout Final Answer 20 没有cout最终答案的输出68有cout最终答案的输出20
The problem is not with the cout
. 问题不在于
cout
。
First, your Odd
and Even
functions should not take pointers, as you are returning the value already. 首先,您的
Odd
和Even
函数不应使用指针,因为您已经在返回值。
Second, you're not initializing the variable cycle
in the Cycle
function. 其次,您无需在
Cycle
函数中初始化变量cycle
。
This code runs correctly: 此代码正确运行:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.