-1
#include <stdio.h>
int main (){
int i, n;
printf("Digite um numero: ");
scanf("%d", &n);
int a;
a = n;
for ( ; a>=0; a--){
if(n%a==0){
i++;
}
}
printf("%d", i);
}
This is my code, it’s not working. His goal is to type a number and he calculates how many divisors that number has. It’s not going, I’m still learning and I have no idea what I did wrong. According to my logic it should be working.
You have to initialize
i
with zero, otherwise it starts with any value (the so-called "junk" memory). And the condition of thefor
must bea > 0
, because if use>=
you will end up making a division by zero and will give error.– hkotsubo
Another detail is that you don’t need to loop all the numbers. Every integer is divisible by 1 and by itself, so testing these is redundant. Tip: https://ideone.com/XeqveD - and see the explanation of the algorithm here: https://answall.com/a/486325/112052
– hkotsubo