Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #10291

Re: Arithmetic error

From Ian Collins <ian-news@hotmail.com>
Newsgroups comp.lang.c
Subject Re: Arithmetic error
Date 2011-09-16 08:56 +1200
Message-ID <9df743F2gmU13@mid.individual.net> (permalink)
References <j4toe7$1ls$1@speranza.aioe.org>

Show all headers | View raw


On 09/16/11 08:50 AM, Andy Foot wrote:
> Hello
>
> I have recently started a distance-learning C course.
>
> I am writing a program to input some numbers and calculate they're mean
> (average). However there is a bug: if the numbers are 1,2,3 then the
> calculation is correct (mean=2) however if the numbers are 1,2 then the
> answer is wrong (mean=1, should be 1.5).
>
> What's going on!
>
> #include<stdio.h>
> void main()
> {
>      char buf[BUFSIZ];
>      int a=0,b=0;
>      while(strcmp(gets(buf),"")!=0){
>          a++; b+=atoi((char*)buf);

atoi should be avoided (it can't indicate an error), have a look at 
strtol instead.

>      }
>      printf("mean=%f",(float)(b/a));

You are casting the result of (int)3/(int)2, which is 1.  Make b a 
double and call it something meaningful like sum.


-- 
Ian Collins

Back to comp.lang.c | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Arithmetic error Andy Foot <foot@dev.null.invalid> - 2011-09-15 20:50 +0000
  Re: Arithmetic error Ian Collins <ian-news@hotmail.com> - 2011-09-16 08:56 +1200
  Re: Arithmetic error Nick Keighley <nick_keighley_nospam@hotmail.com> - 2011-09-15 14:07 -0700
  Re: Arithmetic error "BartC" <bc@freeuk.com> - 2011-09-15 22:34 +0100
    Re: Arithmetic error Ike Naar <ike@sverige.freeshell.org> - 2011-09-15 22:07 +0000
    Re: Arithmetic error Ike Naar <ike@sverige.freeshell.org> - 2011-09-15 22:04 +0000
  Re: Arithmetic error Ben Bacarisse <ben.usenet@bsb.me.uk> - 2011-09-15 22:52 +0100
    Re: Arithmetic error Fred <fred.l.kleinschmidt@boeing.com> - 2011-09-16 11:37 -0700

csiph-web