简体   繁体   English

带有数学问题的 c++ 函数

[英]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.我开始学习 c++ 并解决了这个问题,尝试进行以下计算:place + (place / 10)² 如果 place = 90,它应该是 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这是 TestFunction 标头

#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.我真的不知道在尝试使用 getResult() 或 num1 时我错过了什么,欢迎提供任何建议或简单的解释,谢谢。

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. num1的初始化在place的初始化之前place ,这是不惜一切代价避免的。
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.还有其他方法,但这对您来说可能是最容易获得的。

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

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