C programming: Does scanf not read values 0 and 1 as intended as integers? -
i trying sum of multiples of 2 values.
i used scanf
request integer value twice user.
in code , algorithm created works intended except when user input value of 0 and/or 1.
i want computer able accept value of 0 , result in total of 0 , when accepting 1 total sum of 1 0 gives me odd crash , 1 gives me big value.
/*multiples of 3 or 5: 3,5,6,9; sum 23*/ #include <stdio.h> int main() { int value,value2,limit = 1000; int i,divi,sum = 0; /*read user input first value*/ scanf("%d",&value); /*get sum of multiples of value*/ for(i = value;i < limit;){ sum = sum + i; = + value; } printf("%d\n",sum); printf("done %d\n",value); /*read user input second value*/ scanf("%d",&value2); /*get sum of multiples of value2*/ for(i = value2;i < limit;){ divi = i%value; if((divi)==0){ = + value2; } else { sum = sum + i; = + value2; } } printf("%d\n",sum); printf("done %d\n",value2); return 0; }
the for
loop intended count things off. don't need to, it's more readable. i'll later.
for first loop, have:
for(i = value;i < limit;){ sum = sum + i; = + value; }
this...
- sets initial value of
i
,value
. is...a little unorthodox , might causing confusion. - each iteration, test
i
againstlimit
. - increments
sum
ever-increasing value ofi
. - increases value of
i
value
.
the problem see that, when value
zero, i
never changes.
there's oddity sum
doesn't appear multiples. if value
1
, sum
0, 1, 3, 6, 10, 15...triangular numbers. doesn't sound want.
instead, think want use for
loop intent, counting, , increase sum
repeatedly. like:
for(i = 0;i < limit;i++){ sum = sum + value; }
that says add value
sum
, limit
times.
if did need triangular numbers, may want introduce supplemental variable. if counting isn't want, might want while
loop, instead, readability, like:
while (sum < limit){ sum = sum + value; /* or whatever need, here */ }
but test input value
make sure it's not 0
. no matter how many zeroes add, they're not going bigger limit
...well, unless limit
negative.
Comments
Post a Comment