我正在编写一个函数来返回数组的总和,但我的测试用例显示该特定函数没有输出。有人可以帮忙吗?
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;
}
}
答案 0 :(得分:0)
这是一个更清洁,更易读(imo),更安全。
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;
}