dimanche 3 novembre 2019

Getting wrong results for simple if else statements

I am newbie to programming and recently started working on C++. I have come across hacker-rank and started to learn class vs instance day 4 of 30 Days of starting with programming.Now, here one of the function checks your age and condition like (I am copy pasting my code here)

As we are increasing 3 times using the p.yearPasses function in int main(). It lands on 13(after 3 increment in age) and it should give me teenager but it gives old. I am little perplexed why this is happening and any help will be appreciated.

I have changed the order of if else condition and tried to put age>18 first and went reverse but that didn't help.

#include <iostream>

class Person{
    public:
        int age;
        Person(int initialAge);
        void amIOld();
        void yearPasses();
    };

    Person::Person(int initialAge){
        // Add some more code to run some checks on initialAge
    if (initialAge<0){
        age=0;
        cout<<"Age is not valid, setting age to 0"<<endl;

    }
    else
    age=initialAge;

    }

    void Person::amIOld(){
        // Do some computations in here and print out the correct statement to the console 
    if (age<13)
        cout<<"You are Young"<<endl;
    else if(age>=13 && age<=18)
        cout<<"You are teenager"<<endl;    
    else
        cout<<"You are old";
    }

    void Person::yearPasses(){
        // Increment the age of the person in here
        age +=age;

    }int main(){
    int t;
    int age;
    cin >> t;
    for(int i=0; i < t; i++) {
        cin >> age;
        Person p(age);
        p.amIOld();
        for(int j=0; j < 3; j++) {
            p.yearPasses(); 
        }
        p.amIOld();

        cout << '\n';
    }

    return 0;
}

Now, the input like 10 g

I/P 10 gives:

You are Young.

You are old.

Expected:

You are Young.

You are teenager.

Aucun commentaire:

Enregistrer un commentaire