Ad

I've Made Two Codes But I Can't Interpret Why These Two Are Different And Produce Different Results

- 1 answer

The first code that I made is this...

for (i = 0; startNum + i <= endNum; i++)
    {
        num = startNum + i; // num도 100부터 시작
        
        while (1) // 고집수를 확인하기 위함
        {
            doubleNum = transNumber(num); // 각 자리 수의 곱의 값
            count = count + 1;
            if (doubleNum < 10) {break;}
            
            num = doubleNum;
        }

The second code is the following

 for (i = 0; startNum + i <= endNum; i++){
        num = startNum + i; // num도 100부터 시작
        count = 0;
        while (num > 10) {
            num = transNumber(num);
            count++;
        }
    if (count == goNum)
        {
            printf("%d\n", startNum + i);
            count2 = count2 + 1;
        }
    }

What I thought is that if I make a new variable doubleNum, then it would keep taking in the result of transNumber. Also, since I put the if statement, then it would be the same code as the first code...

However, the results are clearly different, and I'm wondering if there could be a specific explanation for this?

Ad

Answer

In

if (doubleNum < 10) {break;}

the cycle breaks when doubleNum reaches 9 or less.

In

 while (num > 10)

the cycle stops when num reaches 10 or less.

Hence the difference.

Using

while (num > 10) //first code

if (doubleNum <= 10) {break;} //second code

should fix it.

Ad
source: stackoverflow.com
Ad