mercredi 31 janvier 2018

C++ Kaprekar test loop not printing two numbers

I'm having an issue finding out why I can't get 4879 & 5292 to print without creating another else-if to pinpoint those two to divide by a higher unit. I need to not do that.

Problem: a program to test kaprekar numbers less than 10,000

Inputs: none

Outputs: kaprekar numbers

Formulas: squared number = number * number, first half = squared number/unit, second half = remainder of squared number/unit, test = first half + second half

Here's my actual code:

#include <iostream>

using namespace std;

int main()
{
//declare variables 
int num, squaredNum, firstHalf, secondHalf, unit, test;

//initialize number
num = 1;
cout << "Here are all Kaprekar numbers less than 10,000!\n";
cout << "-----------------------------------------------\n" << endl;

//while loop
while(num < 10000){
squaredNum = num * num;
if (squaredNum < 100){
    unit = 10;
}
   else if (squaredNum < 10000){
   unit = 100;
   }
     else if (squaredNum < 1000000){
     unit = 1000;
     }
        else if (squaredNum >= 1000000){
        unit = 10000;
           }
//test if both sides add up to original number                    
firstHalf = squaredNum/unit; //right side
secondHalf = squaredNum%unit; //left side
test = firstHalf + secondHalf;  

if (test == num){
cout << num << " is a Kaprekar! " << firstHalf;
cout << " + " << secondHalf << " is = " << num << endl; //outputs kaprekar number
num++; //increment number
}
num++; //increment & continue to next number
}//end while loop
return 0;
}

If someone could help me figure out where I'm having my issue, that would be great. It has something to do with the zeros when I divide, but I'm not sure what to use for that part.

Aucun commentaire:

Enregistrer un commentaire