我一直在编写一个C程序,它接受一组浮点数,并计算该数据集的平均/中值/模式、方差和标准差。目前,如果输入6到7浮点数作为参数,则这些参数设置为零。然而,当使用少于6个或8个以上的参数时,就没有相同的问题了。下面是这个问题的程序输出示例:
statistics.exe 20 19 17 17 18 15 20 21
Dataset: 20.000 19.000 17.000 17.000 18.000 15.000 0.000 0.000
下面是负责将输入转换为程序可用的浮点数组的代码:
int main(int argc, char *argv[]) {
float *dataset;
int length = argc-1;
dataset = (float *) malloc(argc);
for(int i = 0; i < length; i++) {
dataset[i] = (float)atof(argv[i+1]);
}
}
我对c++编程还比较陌生(来自C++),所以我希望能有一些关于解决这个问题的输入。
发布于 2021-07-09 01:49:25
您的解决方案可能如下所示:
int main(int argc, char *argv[])
{
float *dataset;
int length = argc - 1;
char *e, *p;
dataset = calloc(length,sizeof(float));
for(int i = 0; i < length; ++i) {
dataset[i] = strtof(p = argv[i + 1],&e);
if (e == p || *e) {
fprintf(stderr,"Error converting value '%s'\n",p);
exit(-1);
}
}
}
通过使用strtof
而不是atof
,您将得到一些错误检查。
https://stackoverflow.com/questions/68310224
复制相似问题