简体   繁体   中英

Why does my code calling a function twice?

    #include <stdio.h>
int bolucu(int n){
int temp;
temp=n;
int basamak=0;
while(temp != 0){
    temp/=10;
    ++basamak;
}
int digits = 0;
int m = n;
while (m) {
    digits++;
    m /= 10;
}
digits /= 2;
int tmp = 0, lower_half = 0;
while (digits--) {
    tmp *= 10;
    tmp += n % 10;
    n /= 10;
}
while (tmp) {
    lower_half *= 10;
    lower_half += tmp % 10;
    tmp /= 10;
}
if (basamak % 2==1){
    n/=10;
}
int a;
int b;
a = n;
b=lower_half;
printf("%d %d\n",a,b);
int loopTemp;
for(int i=0;i<10;i++){
    a=3*a+2;
    b=2*b+3;
    if(a>b){
        temp=a;
        a=b;
        b=temp;
    }
    if(a==b){
        printf("Congratulations you caught one!!!\n");
        return 1;
        break;
    }
}
if(a!=b){
    printf("10 tries were not enough!\n");
    return 2;
}
}
int main()
{
    int number;
    printf("\nEnter a number with at least two digits: ");
    scanf("%d",&number);
    bolucu(number);
    while(bolucu(number) != 1){
    printf("\nEnter a new number: ");
    scanf("%d",&number);
    printf("%d",bolucu(number));
    }
    return 0;
}

eg: This is terminal screen.

As you can see there is a second one. First one is true but i don't want second one. How can i get rid of the second calling? (Also sorry for bad code writing, i'm new) What im missing here? And i cant use any library other than stdio.(Like math.h)

The reason for this is because you call the bolucu() function both inside the while loop and in it's condition check. To fix this, call the function and hold it's result in a variable once, and then use that single result in both the check and your print statement. Your main function can be rewritten like so:

int main()
{
    int number;
    printf("\nEnter a number with at least two digits: ");
    scanf("%d", &number);
    int result = bolucu(number);
    while (result != 1)
    {
        printf("\nEnter a new number: ");
        scanf("%d", &number);
        result = bolucu(number);
        printf("%d", result);
    }
    return 0;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM