[英]c++ functions with math problems
我开始学习 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();
}
这是 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);
};
并得到这个结果:
Using getPlace():90
Using getResult(): -2147483648
Using num1: -2147483648
calculate here: 171
我真的不知道在尝试使用 getResult() 或 num1 时我错过了什么,欢迎提供任何建议或简单的解释,谢谢。
您需要跟踪计算完成的时间。
num1
的初始化在place
的初始化之前place
,这是不惜一切代价避免的。
您可以将该计算移动到构造函数中:
TestFunction(std::string userName, int userPlace) {
name = userName;
place = userPlace;
num1 = place + pow(place / 10, 2);
}
还有其他方法,但这对您来说可能是最容易获得的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.