gpt4 book ai didi

c - 使用指针返回数组的总和 - 无输出

转载 作者:行者123 更新时间:2023-11-30 17:04:05 25 4
gpt4 key购买 nike

我正在编写一个函数来返回数组的总和,但我的测试用例显示该特定函数没有输出。有人可以帮忙吗?

double sumArray(int n, double * array) {
// Add your code here
int i;
double sum = 0.000000;
double *ptr;
ptr = array;
if (n == 0) {
return 0.000000;
} else {
for (i = 0; i < n; i++) {
sum = sum + *ptr;
ptr++;
}
return sum;
}
}

最佳答案

这更干净,更易读(我认为),也更安全。

double sumArray(const double * const arr, size_t n) {
// promise the compiler that you won't change anything in the array or the pointer itself
// the size of an array should always be >= 0, so use a size_t
double sum = 0.0;
const double *ptr = arr; // create a const pointer and point it at the array
size_t i; // counter variable
for (i = 0; i < n; ++i) // iterate up to n
sum += *ptr++; // dereference ptr and increment it
return sum;
}


int main(int argc, char **argv) {
double arr[] = { 1.0, 1.5, 2.1 };
printf("%f\n", sumArray(arr, sizeof(arr)/sizeof(double)));
return 0;
}

关于c - 使用指针返回数组的总和 - 无输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35929841/

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