斐波那契测试的错误结果(C++) 我开始学习C++,我的作业是写一个代码,你可以输入5个数字,程序会告诉你每个数字是不是斐波那契数。
我还尝试在isFibonacci函数中使用do/while循环,而不是for循环,但这并没有解决问题斐波那契测试的错误结果(C++) 我开始学习C++,我的作业是写一个代码,你可以输入5个数字,程序会告诉你每个数字是不是斐波那契数。,c++,C++,我还尝试在isFibonacci函数中使用do/while循环,而不是for循环,但这并没有解决问题 #include <iostream> #include <cstdio> using namespace std; //function to test whether a number is a Fibonacci number or not bool isFibonacci (int i) { //special cases with 0 and 1:
#include <iostream>
#include <cstdio>
using namespace std;
//function to test whether a number is a Fibonacci number or not
bool isFibonacci (int i)
{
//special cases with 0 and 1:
if ( i == 0 || i ==1) {
return true;
}
//for all other numbers:
int Fib1;
int Fib2;
int Fib3;
for (Fib3=0; Fib3>=i; Fib3++) {
Fib3 = Fib1 + Fib2;
Fib1 = Fib2;
Fib2 = Fib3;
if (Fib3==i){
return true;
}
else {
return false;
}
}
}
int main ()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
cout << "Please enter 5 numbers;" << endl;
cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i=0; i<5; i++) {
result=isFibonacci (numbers[i]);
if (result == true) {
cout << "Your number " << numbers[i] << " is a Fibonacci number!" << endl;
}
else {
cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << endl;
}
}
return 0;
}
第一个斐波那契数是0,1,1,2,3,5,8,12。
因此,当我输入5个数字时,例如1,2,3,4,5,我应该得到1,2,3和5的是,但4的否。
然而,我的程序声称,除了1之外,这些数字都不是斐波那契数。基本上你的方法是个好主意。但是您在check函数中犯了一些实现错误。比如未初始化的变量和错误的计算。看看你的循环 另外。大数字会有问题 许多非常聪明的人,探索斐波那契数。有整本书可用。还有一篇维基百科文章。看 或者看看那本书: 或者也在这里 因此,我不会重新发明轮子。这是您的修订版软件:
#include <iostream>
#include <cmath>
#include <numeric>
// Positive integer ? is a Fibonacci number
// If and only if one of 5?2 + 4 and 5?2 - 4 is a perfect square
// from The(Fabulous) FIBONACCI Numbers by Alfred Posamentierand Ingmar Lehmann
// Function to test whether a number is a Fibonacci number or not
bool isFibonacci(int w)
{
{
double x1 = 5 * std::pow(w, 2) + 4;
double x2 = 5 * std::pow(w, 2) - 4;
long x1_sqrt = static_cast<long>(std::sqrt(x1));
long x2_sqrt = static_cast<long>(std::sqrt(x2));
return (x1_sqrt * x1_sqrt == x1) || (x2_sqrt * x2_sqrt == x2);
}
}
int main()
{
bool result;
int numbers[5];
int i;
//asking for the 5 numbers
std::cout << "Please enter 5 numbers;" << std::endl;
std::cin >> numbers[0] >> numbers[1] >> numbers[2] >> numbers[3] >> numbers[4];
// giving back the result
for (i = 0; i < 5; i++) {
result = isFibonacci(numbers[i]);
if (result == true) {
std::cout << "Your number " << numbers[i] << " is a Fibonacci number!" << std::endl;
}
else {
std::cout << "Your number " << numbers[i] << " is not a Fibonacci number!" << std::endl;
}
}
return 0;
}
Fib3=Fib1+Fib2;-这是假的,因为您从未初始化过变量。必须初始化变量。此外,循环中的条件也不充分,因为Fib3仍在循环中修改!如果有人对数学感兴趣,那么这种方法之所以有效,是因为函数的隐式属性。如果你在数学学习中还没有从线性递归序列中推导出这些公式,那就准备好享受它吧,因为这是大学数学中最有趣的阶段之一。这对你很有帮助,非常感谢!我刚刚开始,还有很多东西要学