New to C: whats wrong with my program? -


i know way around ruby pretty , teaching myself c starting few toy programs. 1 calculate average of string of numbers enter argument.

#include <stdio.h> #include <string.h>  main(int argc, char *argv[]) {    char *token;    int sum = 0;    int count = 0;    token = strtok(argv[1],",");    while (token != null)    {      count++;      sum += (int)*token;      token = strtok(null, ",");    }   printf("avg: %d", sum/count);  printf("\n");  return 0; } 

the output is:

mike@sleepycat:~/projects/cee$ ./avg 1,1 avg: 49 

which needs adjustment.

any improvements , explanation appreciated.

in line: sum += (int)*token; casting char int takes ascii value of char. 1, value 49.

use atoi function instead:

sum += atoi(token); 

note atoi found in stdlib.h file, you'll need #include well.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -