我正在做一个非家庭作业的问题,无论我怎么尝试都无法解决。
这道题来自 Project Euler,涉及求解偶数斐波那契数并将它们相加,我选择这道题是为了学习更多关于函数、指针和处理大数的机会,最好不要复制它们的值,而是传递一个内存地址。
我目前有以下内容:
/*Second attempt at fibo 4mil
problem.*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
//MAX is 20 for testing reasons
//Actual value is MAX 0X3D0900
#define MAX 20
//Function will accept even fibo numbers
//then sum them together for output later
void evenCount (double* evenPoint);
int main(void){
double firstVar = 0;
double secondVar = 1;
double thirdVar;
double modVar = 2;
double sumVar;
double count;
for(count = 0; count < MAX; count++){
thirdVar = firstVar + secondVar;
secondVar = firstVar;
firstVar = thirdVar;
if(fmod(firstVar, modVar) == 0){
evenCount(&firstVar);
}
printf("Currently: %.2f\n", firstVar);
}
sumVar = &evenCount();
printf("Final even sum is: %f\n", sumVar);
return 0;
}
void evenCount (double* evenPoint){
double tempOne, tempTwo, tempThree;
tempOne = *evenPoint;
tempThree = tempOne + tempTwo;
tempTwo = tempOne;
tempOne = tempThree;
evenPoint = &tempOne;
}
我无法确定来自 main()
的数据是否已正确传递给 evenCount
函数,以便对它们求和并更新其值以进行打印在 main()
的末尾。
我的问题是:
- 我是否需要
evenCount
中的第二个双指针来传递最终值,或者我是否可以只引用一个值在它循环时更新它? main()
是否需要一个指针,以便指针可以引用evenCount
指针?
我真的很感激任何帮助,因为我已经购买了 Safari 在线订阅,旁边有“C A 引用手册”,但我就是想不通。另外,我阅读了这个问题,它在某种程度上回答了我的问题,但是这个人正在使用多个函数原型(prototype)。
too few arguments to function and can't be used as a function---- beginning C
感谢任何看起来的人
最佳答案
我不完全清楚 evenCount()
函数应该做什么。
事实是你调用它的方式不对 - sumVar = &evenCount();
甚至错了两次,因为它缺少参数和 &
没有意义 - 它不会做你可能想要的。
让我们看看:
void evenCount (double* evenPoint){
double tempOne, tempTwo, tempThree;
这里你定义了三个自动变量,但是它们还没有得到值。
tempOne = *evenPoint;
tempThree = tempOne + tempTwo;
你希望这里的 tempTwo
是什么?
tempTwo = tempOne;
tempOne = tempThree;
evenPoint = &tempOne;
您可能在这里的意思是*evenPoint = tempOne
,但我不确定。
}
我想您想要一种方法来根据斐波那契数列“迈出一步”。那么让我们看看:
为了创建“下一个”斐波纳契数,您需要前两个数并将它们相加。所以一个“步骤”可以在像
这样的函数中完成void fibStep(double * curr, double *prev) {
double new = *curr + *prev;
*prev = *curr;
*curr = new;
}
然后
int main(void){
double firstVar = 0;
double secondVar = 1;
double sumVar = 0;
int count; // no need to have this as a double...
for(count = 0; count < MAX; count++){
fibStep(&secondVar, &firstVar);
if(fmod(secondVar, 2) == 0){
sumVar += secondVar);
}
printf("Currently: %.2f\n", secondVar);
}
printf("Final even sum is: %f\n", sumVar);
return 0;
}
关于C从函数传递双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26653560/