Home > Blockchain >  Why does my code calling a function twice?
Why does my code calling a function twice?

Time:11-28

    #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;
}

e.g: 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)

CodePudding user response:

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;
}
  •  Tags:  
  • c
  • Related