Could you please help me out to understand why the If statement is not executing. Thank you for your time.
void allPerfects (int a, int b){
int minVal = minN(a, b);
int maxVal = maxN(a, b);
int sum =0;
vector<int> v;
while (minVal < maxVal){
v.push_back(minVal);
minVal++;
}
for (int i = 0; i < v.size() ;i++){
for (int j = 0; j < i; j++){
sum += v[j];
}
if (sum == v[i]){
printInt(v[i], false); printStr(" is a perfect number!", true);
}
}
}
Even if there aren't any bugs in your code you'll only get a print out for:
allPerfects(a, b);
if there are consecutive integers a
, a + 1
, ... , a + n
that sum up to a + n + 1 < b
.
This is only true for:
1 + 2 == 3
and
0 + 1 + 2 == 3
so a
has to be 0
or 1
and b
has to be greater than or equal to 4
.
Edit: But this will only happen if you reset your sum
:
for (int i = 0; i < v.size() ;i++){
sum = 0; // This line is missing.
for (int j = 0; j < i; j++){
sum += v[j];
}
if (sum == v[i]){
printInt(v[i], false); printStr(" is a perfect number!", true);
}
}
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.