I was writing a program which accepted an integer value, than picked out each number at each decimal value, checked if that was a multiple of 3, and if it was, added it all up.
First, here's the code I wrote:
I used Visual Studio 2003 to compile the above (overkill, I know. But I could get it cheap so I might as well use it).Code:#include <stdio.h> int i_summultofthree(int i) { int sum; char s[256]; sum = 0; sprintf(s, "%d", i); for(i=0;s[i]==0; i++) { if(s[i]%3 == 0) { i = s[i] - 48; sum = sum + i; } } return sum; } void main() { int i; i = 123456789; printf("%d\n", i_summultofthree(i)); }
The problem is, "s[i]==0" is not returning any statements at all so the entire loop spins round and round infinitely.
I can make the above code work if I simply change the conditional to "s[i] > 0", but I'm curious why the conditional is not working as it is.
I've also tried
and changing the sprintf toCode:s[i] == '\0'
None of it works except "s[i]>0".Code:sprintf(s, "%d\0", i);
Can somebody tell me why?



LinkBack URL
About LinkBacks


