jeudi 25 novembre 2021

If else condition gets activated without sense [closed]

Hi I wanted to know if someone can explain to me why my Code never goes into the if condition even-tough the condition is true. And if I if(use number <= -1){...} it is always activated.

My task was it to create a code which checks if a number is divisible by eleven without using %

I want that if I have a negative number it transforms into a positive.

Thank you for your help

Down I have the full code

As an example if i put in -11 the variable number stays -11 instead of 11 (the positive value) and returns a false (it means that -11 wouldn't be divisible by eleven)

bool divisible_by_eleven(unsigned number) {

//The Code is supposed to check if a number is divisible by eleven
if(number < -1) number = -number; 
//Check if the number is negative and then make it positive



printf("Number: %d \n", number); 
// I used this for debugging the printf part is unnecessary 

int i = 11;
// instead of a for loop i did it this (please don't ask why I was 

//tired and couldn't think straight anymore when I started coding

 //this
/*
the loop checks if a number is divisible by eleven by checking if 
the number is 11 or smaller than 11. if it is smaller than it 
doubles i (to check if it is a multiple of 11) if the number is the 
same as i than it is also divisible by eleven and if i becomes 
bigger than the number it means the number isnt divisible by eleven

*/
while(i <= number){ 
    if(i == number){
        return true;
    }else{}
    if(i > number){
        return false;
    }else{}
    i = i + 11;
}

return false;```

Aucun commentaire:

Enregistrer un commentaire