【问题标题】:How can I make my program exit the for loop when it reaches 10000? C++如何让我的程序在达到 10000 时退出 for 循环? C++
【发布时间】: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 &lt;= 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 &lt;= 10000) 似乎是正确的方法,但您必须正确使用它(例如声明f outsidebefore循环,并给它一个初始值
  • 你总是可以添加一行像if (f &gt; 10000) break;..虽然可能不是最好的解决方案

标签: c++ function primes fibonacci


【解决方案1】:

一种方法是检查每次迭代的条件,并在f 超过 10000 时检查循环 break

for (int x = 3; x <= 10000; x++)
    {
        int f = fibonacci(x);
        
        if(f > 10000)
            break;
            
        if (isPrime(f))
        {
            cout << setw(2) << nCounter << setw(18) << f << endl;
            nCounter++;
        }
}

您也可以通过将其转换为 while 循环来做到这一点,但为此您必须在循环外声明和初始化 fx

    int x = 3;
    int f = fibonacci(x);
    while(f <= 10000)
    {
        if (isPrime(f))
        {
            cout << setw(2) << nCounter << setw(18) << f << endl;
            nCounter++;
        }
        x++;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2011-01-22
    • 1970-01-01
    相关资源
    最近更新 更多