So, I’ve started programming classes last year. I would like to know how i can make a function in a class that lets me check if a variable has reached a certain threshold and then modify it.
I tried this but i think it just stops at the cycle and never resumes.
It is public and i call it through the main.
This is what I’ve tried so far:
class Numbers{
private:
int Limit, Current, counter;
public:
void addCurrent(int a) { Current += a; }
int getCurrent() {return Current; }
int getLimit() {return Limit; }
int getCounter() {return counter; }
void Check() {
while (true) {
if (Current >= Limit) {
counter++;
Current -= Limit;
Limit = Limit * counter;
}
}
}
};
I call it in the main like this:
#include <iostream>
using namespace std;
int main(){
Numbers.one;
one.Check();
one.addCurrent(200);
cout<< one.getLimit() << "/" << one.getCurrent() << "/" << one.getCounter();
}
Since I’m at a really beginner level I would like to keep it simple, but any help is appriciated.
Thanks
>Solution :
You put your logic into addCurrent:
class Numbers{
private:
int Limit = 1;
int Current = 0;
int counter = 0;
public:
void addCurrent(int a) {
Current += a;
Check();
}
int getCurrent() {return Current; }
int getLimit() {return Limit; }
int getCounter() {return counter; }
void Check() {
while (Current >= Limit) {
counter++;
Current -= Limit;
Limit = Limit * counter;
}
}
};
int main(){
Numbers one;
one.addCurrent(200);
cout<< one.getLimit() << "/" << one.getCurrent() << "/" << one.getCounter();
}
Note that I had to make some assumptions about what behavior you want and what values Limit, Current, and counter should have initially. It’s also not clear if you want the Check logic to continue until Current < Limit or if you want it applied once.