Weird bug in my program?
Dec 10, 2015 at 5:12pm UTC
This is a program to find a happy number but it's not entirely working. For instance, if you put in 5555/86, it will work. However when you put in 32 it should work to get 1 however it doesn't? It says y holds 1 yet it wont break out of my loop?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
// Example program
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int lenH(int x);
int main()
{
bool noty = true ;
stringstream convert;
char response;
string a;
cin >> a;
int counter = 0;
int *x = new int [a.size()];
int *total = new int [a.size()];
int ye = 0;
int length;
for (unsigned int i = 0; i < a.length(); i++) {
x[i] = a[i];
x[i] = x[i] - 48;
total[i] = x[i] * x[i];
cout << total[i] << endl;
ye = ye + total[i];
cout << x[i] << endl;
}
while (counter < 1000 && ye != 1) {
length = lenH(ye);
int *X = new int [length];
int *ay = new int [length];
counter++;
string bob;
convert << ye;
bob = convert.str();
ye = 0;
for (unsigned int z = 0; z < length; z++) {
X[z] = bob[z];
X[z] = X[z] - 48;
ay[z] = X[z] * X[z];
ye = ye + ay[z];
cout << ye << '\n' ;
}
delete [] X;
}
if (ye == 1 || ye == 10) {
cout << endl << ye << " Is a happy number\n" ;
}
else
cout << endl << ye << " Is not a happy number\n" ;
delete [] x;
delete [] total;
cin >> response;
return 0;
}
int lenH(int x) {
if (x >= 100000){
return 6;
}
else if (x >= 10000){
return 5;
}
else if (x >= 1000) {
return 4;
}
else if (x >= 100) {
return 3;
}
else if (x >= 10) {
return 2;
}
else
return 1;
}
Dec 10, 2015 at 6:27pm UTC
Have you tried stepping through it with a debugger, so that you can see why it's behaving the way it does?
Topic archived. No new replies allowed.