我非常了解红宝石,并从一些玩具程序开始自学C语言.这个只是计算我作为参数输入的一串数字的平均值.
#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;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
mike@sleepycat:~/projects/cee$ ./avg 1,1
Avg: 49
Run Code Online (Sandbox Code Playgroud)
这显然需要一些调整.
任何改进和解释将不胜感激.
查找sscanf或atoi作为函数将字符串(字符数组)转换为整数.
与高级语言不同,C不会自动在字符串和整数/实数数据类型之间进行转换.