簡體   English   中英

我的 function 應該使用什么返回類型來打印斐波那契數字?

[英]What return type should I use for my function to print Fibonacci numbers?

我正在嘗試編寫一個 function 來打印 x 和 y 范圍之間的所有斐波那契數。 我幾乎有了它,但我不知道 function genFib(int min, int max){我認為 bool 是正確的,但是當我測試代碼時,行cout << genFib(5, 20) << endl; 打印5 8 13 0在末尾添加零。 我應該使用什么返回類型來避免最后出現零打印? 這是我當前的所有代碼。

#include <iostream>
#include <cmath>
using namespace std;

bool perfectSquare(int x){
    int s = sqrt(x);
    return (s*s == x);
}
bool isFibonacci(int n){
    return perfectSquare(5*n*n + 4) ||
           perfectSquare(5*n*n - 4);
}

bool genFib(int min, int max){
    int newMax = 0, newMin = 0;
    if(min > max){
        newMax = min;
        newMin = max;
    }else{
        newMax = max;
        newMin = min;
    }
    cout << "Fib numbers: ";
    for(int i = newMin; i <= newMax; i++)
        if(isFibonacci(i)) cout << i << " ";
    return false;
}

int main(){
    cout << genFib(5, 20) << endl; 
    return 0;
}

您看到的最后一個 0 在那里,因為您從genFib()返回 false ,然后打印它。 因為您正在打印genFib()方法中的所有內容,所以您不需要打印該方法的結果,或從中返回任何內容。 如果您嘗試以下操作,您將不會打印genFib()的結果,即您的尾隨 0。

int main(){
    int x = 372; // Simply a random number
    genFib(5, 20);
    return 0;
}

由於您也不關心genFib()的返回值,因此您應該返回void而不是false 如果您打印該方法的結果,這將阻止打印任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM