简体   繁体   中英

c++ functions with math problems

I'm starting learning c++ and stepped on this problem, trying to make the following calculation: place + (place / 10)² which if place = 90 it should be 171.

    #include <iostream>
    #include <iomanip>
    #include <cmath>
    #include "TestFunction.h"

    using namespace std;

    int main() {
        TestFunction test1 ("John", 90);
        test1.getInfo();
    }

here is the TestFunction header

#include <iostream>
#include <string>
#include <iomanip>

class TestFunction {

public:
    TestFunction(std::string userName, int userPlace) {
        name = userName;
        place = userPlace;
    }

    int getPlace() {
        return place;
    }

    int getResult() {
        return num1;
    }

    void getInfo() {
        std::cout << "Using getPlace():" << getPlace() << std::endl;
        std::cout << "Using getResult(): " << getResult() << std::endl;
        std::cout << "Using num1: " << num1 << std::endl;
        std::cout << "calculate here: " << getPlace() + pow(getPlace() / 10, 2) << std::endl;
    }

private:
    std::string name;
    int place;
    int num1 = place + pow(place / 10, 2);
};

and get this result:

Using getPlace():90
Using getResult(): -2147483648
Using num1: -2147483648
calculate here: 171

I really don't know what I am missing when trying to use getResult() or num1, any advice or simple explanation will be welcome, thanks.

You need to keep track of when your calculations are done.
The init of num1 is done earlier than the initialisation of place , which is something to avoid at all cost.
You could move that calculation into the constructor:

TestFunction(std::string userName, int userPlace) {
        name = userName;
        place = userPlace;
        num1 = place + pow(place / 10, 2);
    }

There are other ways, but this is probably most accessable to you.

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