我非常了解 ruby,并且正在从一些玩具程序开始自学 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;
}
输出是:
mike@sleepycat:~/projects/cee$ ./avg 1,1
Avg: 49
这显然需要一些调整。
如有任何改进和解释,我们将不胜感激。
最佳答案
寻找 sscanf
或 atoi
作为将字符串(字符数组)转换为整数的函数。
与高级语言不同,C 不会自动在字符串和整数/实数数据类型之间进行转换。
关于c - C 的新手 : whats wrong with my program?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4320278/