我做了一個關于斐波那契程式的程式。我想重復這個程式,所以我使用了 do-while 回圈。但是,似乎上一個結果中的最后兩個數字不斷出現。它應該重置回第一個任期。請幫助我如何到達那里。
#include<iostream>
using namespace std;
void printFibonacci(int n){
static int n1=1, n2=1, n3=0;
if(n>0){
n3 = n1 n2;
n1 = n2;
n2 = n3;
cout<<n3<<" ";
printFibonacci(n);
}
}
int main(){
int n;
cout<<"Enter the number of elements: ";
cin>>n;
cout<<"Fibonacci Series: ";
cout<<"0 "<<"1 ";
printFibonacci(n-2); //n-2 because 2 numbers are already printed
return 0;
}
uj5u.com熱心網友回復:
當您第一次運行代碼時,變數 t1、t2 和 nextTerm 的值正在發生變化。因此,在再次重復相同的代碼之前,您需要再次設定這些變數的默認值。試試這個:
#include <iostream>
using namespace std;
int main (){
int i, n, t1=1, t2=1, nextTerm=0;
cout << "Fibonacci Program" << endl;
do{
t1=1;
t2=2;
nextTerm=0;
cout << "How many elements? ";
cin >> n;
if(n>=1){
cout << "Sequence: ";
for (int i = 1; i <= n; i){
if(i == 1) {
cout << t1 << " ";
continue;
}
if(i == 2) {
cout << t2 << " ";
continue;
}
nextTerm = t1 t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << " ";
}
cout << endl;
}
else{
cout << "Thank you for using the program." << endl;
}
}
while(n>=1);
return 0;
}
uj5u.com熱心網友回復:
您的代碼的問題是您沒有在回圈完成后重置變數。所以要解決這個問題,只需在do-while回圈中定義你的變數:
do {
int t1 = 1, t2 = 1, nextTerm = 0;
..或在 1 個回圈完成后重置您的變數:
else {
cout << "Thank you for using the program." << endl;
}
t1 = 1, t2 = 1, nextTerm = 0;
但n必須在回圈之外定義(正如您所做的那樣):
std::cout << "Fibonacci Program" << std::endl;
int n;
do {
也不需要創建變數i:
int /*i,*/ t1 = 1, t2 = 1, nextTerm = 0;
..因為您稍后在此處的 for 回圈中創建了它:
for (int i = 1; i <= n; i) {
另外,請考慮不要在您的代碼中使用以下內容:
using namespace std;
..因為它被認為是一種不好的做法。有關這方面的更多資訊,請查看為什么被using namespace std認為是一種不好的做法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438733.html
