简体   繁体   中英

No output? C++14

So I'm trying to do a challenge called 3n+1, where I have to tell how many times the program has to multiply or divide until n=1 but I don't get any output from the program. Please help? ps I'm using C++ 14

#include <iostream>
using namespace std;
int n;
int d=0;
int main() {
    cin>> n;
    for(int i=n; i<=1;){
        if(n=1){
            cout<< d;
        }
        else if(n%2==0){
            d++;
            n/2;
        }
        else{
            d++;
            n*3+1;
        }
    }
    return 0;
}

Possible fix:

#include <iostream>
using namespace std;
int main() {
    int n; // you don't need the values to be global
    int d=0;
    cin>> n;
    for(; ;){ // deleted i because it wasn't used
        if(n<=1){ // compare here, don't assign here
            cout<< d;
            break; // exit the loop
        }
        else if(n%2==0){
            d++;
            n=n/2; // please update n here
        }
        else{
            d++;
            n=n*3+1; // also please update n here
        }
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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