【发布时间】:2021-02-14 02:01:35
【问题描述】:
for (int x = 3; x <= 10000; x++)
{
int f = fibonacci(x);
if (isPrime(f))
{
cout << setw(2) << nCounter << setw(18) << f << endl;
nCounter++;
}
}
cout << "Enter any character to quit: ";
cin.get();
正如标题所说,我一直在努力寻找一种合适的方式来退出我的 for 循环,但也要以正确的方式使用我的函数。我尝试了while (f <= 10000) 和其他一些方法,但答案总是不同。
该程序旨在运行斐波那契数列,并检查数列中的数字是否为“素数”,直到斐波那契数达到 10000 或其他。
目前,当它运行时,它会继续运行,直到达到一个大的负数。
我不能使用向量
整个代码:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
bool isPrime(long long n);
long long fibonacci(int n);
int main()
{
double nCounter = 1;
cout << "Fibonacci Primes by Luke" << endl;
cout << endl;
cout << setw(2) << "n" << setw(18) << "Fibonacci Prime" << endl;
cout << "==" << setw(18) << "===============" << endl;
for (int x = 3; x <= 10000; x++)
{
int f = fibonacci(x);
if (isPrime(f))
{
cout << setw(2) << nCounter << setw(18) << f << endl;
nCounter++;
}
}
cout << "Enter any character to quit: ";
cin.get();
}
bool isPrime(long long n)
{
for (int i = 2; i < n; i++)
{
if (n % i == 0)
return false;
}
return true;
}
long long fibonacci(int n)
{
if (n <= 1)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
这是我尝试使用的 while,但 long long fibonaci 总是返回 '2' 并创建一个无限循环。
int x = 3;
long long f;
while (f <= 10000)
int f = fibonacci(x);
if (isPrime(f))
{
cout << setw(2) << nCounter << setw(18) << f << endl;
nCounter++;
}
【问题讨论】:
-
您确定要计算 10000 个斐波那契数吗?这些数字非常大,不适合
int。 -
我相信你完全误读了你的家庭作业。不要求您计算前 10000 个斐波那契数。您被要求计算最大为 10000 的所有斐波那契数。这是完全不同的两件事。
-
我用整个代码更新了我的帖子。我被要求将所有素数斐波那契数计算为 10000,程序可以运行,但在命中时不会退出。
-
您的
while (f <= 10000)似乎是正确的方法,但您必须正确使用它(例如声明foutside 和 before循环,并给它一个初始值 -
你总是可以添加一行像
if (f > 10000) break;..虽然可能不是最好的解决方案
标签: c++ function primes fibonacci