简体   繁体   English

未在函数 C++ 中执行的循环

[英]Loops not executing in functions C++

Here's my code.这是我的代码。 Whenever I run the program, I expect that the cout statement in the for loop in the function Binary() to execute.每当我运行程序时,我希望 function Binary()中的for 循环中的cout语句能够执行。 But whenever I input something, it gives me 0但是每当我输入一些东西时,它都会给我0

#include<iostream>
#include<math.h>
using namespace std;
long int Binary(int x){
    int temp=0,res=0;
    for(int i=x;i<0;i--){
        temp++;
        res=res+ pow(10,temp)*(i%2);
        i=i/2;
        cout<<i<<"  "<<res<<endl;
    }
    return res;
} 
int main(){
    int x; cin>>x;
    cout<<endl<<Binary(x);
    return 0;
}

I think the condition in your for loop is the opposite way round than your expect it.我认为您的 for 循环中的条件与您的预期相反。 You seem to want it to continue looping until i<0 .您似乎希望它继续循环直到i<0 But it will actually loop while i<0 .但它实际上会i<0时循环。 The condition is already not true when you enter the loop, so it will finish immediately without doing any iterations.当你进入循环时,条件已经不成立,所以它会立即结束而不做任何迭代。

You just have to change the loop i check.你只需要改变i检查的循环。

#include<iostream>
#include<math.h>
using namespace std;
long int Binary(int x){
    int temp=0,res=0;
    for(int i=x;i>0;i--){
        temp++;
        res=res+ pow(10,temp)*(i%2);
        i=i/2;
        cout<<i<<"  "<<res<<endl;
    }
    return res;
} 
int main(){
    int x; cin>>x;
    cout<<endl<<Binary(x);
    return 0;
}

Check the live version here http://cpp.sh/95z74在此处查看实时版本http://cpp.sh/95z74

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM