I'm having trouble getting the outcome. The current program I wrote is to multiply each digit to get the next number and the next until the number becomes a single digit.
For example,
77 - 49 - 36 - 18 - 8 : repeats 4 times
679 - 378 - 168 - 48 - 32 - 6 : repeats 5 times
The problem with my code is that the result doesn't come out after numbers that process %d times\n
I'm guessing that the output()
is the probelem.. but I'm really stuck on finding the error.
#include <stdio.h>
#pragma warning (disable : 4996)
void inputUInt(int*, int*, int*);
void myFlush();
int transNumber(int);
void output(int, int, int);
int main()
{
int start, end, gNum; // start number, end number, how many times until the number becomes a single digit
inputUInt(&start, &end, &gNum);
output(start, end, gNum);
return 0;
}
void inputUInt(int* startp, int* endp, int* gNump)
{
while (1) {
printf("#start number : ");
scanf("%d", startp);
if (*startp >= 100 && getchar() == '\n') {
break;
}
else { ; }
myFlush();
}
while (1) {
printf("#last number : ");
scanf("%d", endp);
if (*endp <= 10000 && *endp > * startp && getchar() == '\n') {
break;
}
else { ; }
myFlush();
}
while (1) {
printf("# gNum : ");
scanf("%d", gNump);
if (*gNump > 0 && *gNump <= 10 && getchar() == '\n') {
break;
}
else { ; }
myFlush();
}
return;
}
void myFlush()
{
while (getchar() != '\n') {
;
}
return;
}
int transNumber(int num)
{
if (num >= 1000) {
num = (num / 1000) * ((num % 1000) / 100) * ((num % 100) / 10) * ((num % 10) / 1);
}
else if (num >= 100) {
num = (num / 100) * ((num % 100) / 10) * ((num % 10) / 1);
}
else if (num >= 10) {
num = (num / 10) * ((num % 10) / 1);
}
else { ; }
return num;
}
void output(int start, int end, int gNum)
{
int i, num, transN, count = 0, gNumTotal = 0;
printf("numbers that process %d times\n", gNum);
for (i = start; i <= end; i++) {
num = i;
transN = transNumber(num);
while (transN > 10) {
count++;
}
}
if (count == gNum) {
printf("%d\n", i);
gNumTotal++;
}
else { ; }
printf("total numbers : %d numbers", gNumTotal);
return;
}
You have to call transNumber()
repeatedly in the loop. Otherwise, transN
never changes, so the loop never ends.
The code that prints i
needs to be inside the for
loop, and you need to reset count
back to 0
before each while
loop.
for (i = start; i <= end; i++) {
num = i;
count = 0;
while (num > 10) {
num = transNumber(num);
count++;
}
if (count == gNum) {
printf("%d\n", i);
gNumTotal++;
}
}
You don't need:
else { ; }
after each if
. If you don't need to do anything when the condition is false, just leave it out.