Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When printing X variable it prints "123" then the actual variable value

When you type in 4 it should output only 2 but instead it outputs 12, same goes for 6 it outputs 123 and so on and so forth

int main() {
    int salary, yearsOfService, X; //rounded off for computation of bonuse
    string companyName;
    
    std::cin >> yearsOfService;
    
    if (yearsOfService >= 1){ //X is rounded off case number for amount of years
        X = 0;
        X = 1;
        std::cout << X;
        
        if (yearsOfService>=2){
            X = 0;
            X = 2;
            std::cout << X;
        }
        if (yearsOfService>=5){
            X = 0;
            X = 3;
            std::cout << X;
        }
        if (yearsOfService>=6){
            X = 0;
            X = 4;
            std::cout << X;
        }
        if (yearsOfService>=11){
            X = 0;  
            X = 5;
            std::cout << X;
        }
            
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your program is doing exactly what you told it to do. It will run down and execute those statements in sequence. It sounds like what you’re trying to do is this:

X = 0;
if (yearsOfService >= 11)
    X = 5;
else if (yearsOfService >= 6)
    X = 4;
else if (yearsOfService >= 5)
    X = 3;
else if (yearsOfService >= 2)
    X = 2;
else if (yearsOfService >= 1)
    X = 1;

if (X != 0) std::cout << X;

Another way instead of using else is to just add 1 to X any time one of these conditions is satisfied. Then you can run them in any order.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading