gpt4 book ai didi

c - 如何比较传递给函数的数组元素的值

转载 作者:行者123 更新时间:2023-11-30 15:02:57 27 4
gpt4 key购买 nike

我正在尝试编写一个函数,它以以下格式从用户那里获取输入:0.3,0.2,1,数据类型为:float,float,int。如果两个 float 的值为 0.0,则数据输入完成。我初始化了三个数组

float col1Train[1000];
float col2Train[1000];
int col3Train[1000];

在主函数中(可以合理地假设用户的数据条目少于1k),并像这样调用该函数:

nTrainSets = readTrainingData(&col1Train, &col2Train, &col3Train);

现在,我的问题是 IF 条件(如下标记)使我的程序崩溃,我不知道为什么。我想检查包含的数组元素是否为零..

此外,同一语句的替代表述(至少我相信它是相同的?)没有编译引用 float 和 *float 的不匹配 - 为什么会这样/我该如何解决这个问题?

int readTrainingData(float *col1[], float *col2[], int *col3[])
{
int i = 0;
int scanfReturn = scanf("%f,%f,%d", &col1[i], &col2[i], &col3[i]);
while (scanfReturn == 3) {
printf ("read: %f, %f, %d", col1[i], col2[i], col3[i]); // Debug statement, execution succeeds
if (*col1[i] == 0.0f && *col2[i] == 0.0f) { // Causing the error
//if (*(col1 + i) == 0.0f && *(col2 + i) == 0.0f) { // Not even compiling
col1[i] = NULL;
col2[i] = NULL;
col3[i] = NULL;
break;
}
++i;
scanfReturn = scanf("%f,%f,%d", &col1[i], &col2[i], &col3[i]);
}
return i - 1;
}

谢谢!

最佳答案

float col1Train[1000];
float col2Train[1000];
int col3Train[1000];

考虑在此处使用struct:

struct train {
float col1;
float col2;
int col3;
};

struct train Train[1000];

it can reasonably be assumed that there are less than 1k data entries by the user

永远不要假设任何事情。只需在函数调用中传递元素数量即可。所以而不是

nTrainSets = readTrainingData(&col1Train, &col2Train, &col3Train);

使用

nTrainSets = readTrainingData(1000, &col1Train, &col2Train, &col3Train);

此外,将数组有效地传递给函数就是将指向其第一个参数的指针传递给函数。所以,这样调用它:

nTrainSets = readTrainingData(1000, col1Train, col2Train, col3Train);

然后函数原型(prototype)也需要更改。而不是

int readTrainingData(float *col1[], float *col2[], int *col3[])

要么写

int readTrainingData(size_t size, float col1[], float col2[], int col3[])

int readTrainingData(size_t size, float * col1, float col2, int col3)

两者基本相同。我更喜欢 float * col1 变体,但有人可能会争辩说,float col1[] 文档表明需要一个实际的数组,而不仅仅是指向单个值的指针。

int scanfReturn = scanf("%lf,%lf,%d", &col1[i], &col2[i], &col3[i]);

由于 scanf 无论如何都需要一个指针,所以只需计算一个指针:

int scanfReturn = scanf("%lf,%lf,%d", col1 + i, col2 + i, col3 + i);

现在,与 printf 不同,其中 "%f" 需要一个 double 参数和 float由于类型提升规则而被提升为 double(并且 "%lf" 后来才被允许用作 "%f" 的同义词) >),scanf 系列函数实际上必须区分两种数据类型。因此,要扫描 double,您可以使用 "%lf",但对于 float(您在此处使用的),您必须克制"%f" 像这样:

int scanfReturn = scanf("%f,%f,%d", col1 + i, col2 + i, col3 + i);

然后

    if (*(col1 + i) == 0.0f && *(col2 + i) == 0.0f) {

或 (col1[i] == 0.0f && col2[i] == 0.0f) {

世界与 Cish 的方式完美配合:

    if (!col1[i] && !col2[i]) {

.

        col1[i] = NULL;
col2[i] = NULL;
col3[i] = NULL;

这里,请使用0而不是NULL,因为NULL可能是一个指针,因此无法分配给非指针变量。

        col1[i] = 0;
col2[i] = 0;
col3[i] = 0;

最后总结“永远不要假设任何事情”部分:在 i 增量中,测试缓冲区溢出:

    if (++i == size-1) {
col1[i] = 0;
col2[i] = 0;
col3[i] = 0;
break;
}

关于c - 如何比较传递给函数的数组元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911697/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com