problem with arrays

Hi,

I am trying to calculate the silver ratio via a recurrence relation but when i run the code i just get incorrect values for all but the first 3 values.

can anyone tell me where i have gone wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  #include<iostream>
#include<cmath>
#include<fstream>
#include<iomanip>
#include<vector>

using namespace std;

int main(){

ofstream silver("silver.txt");
int N;

cout<< "Please enter your indice" << endl;
cin>> N ;
cout<< "Indice Value" << setw(15) << "Actual Value" << setw(32) << "Recurrence Value (Float)" << setw(28) << "Recurrence Value (Double)" << endl;
silver<< "Indice Value" << setw(15) << "Actual Value" << setw(32) << "Recurrence Value (Float)" << setw(28) << "Recurrence Value (Double)" << endl;
 for (int i=0 ; i<=N; ++i){

 
 vector<float>  lfloat(50);
 vector<double> ldouble(50);
 double k= pow(((-1+sqrt(5))/2),i); // silver ratio

 lfloat.at(0)=1.0;
 ldouble.at(0)=1.0;
 lfloat.at(1)=(-1+sqrt(5))/2;
 ldouble.at(1)=(-1+sqrt(5))/2;
   
   if (i<2){

   
  cout<< setw(15) << left << i << setprecision(15) << setw(20) << left << k << setw(27) << left << lfloat.at(i) << left << ldouble.at(i) << endl;
 silver<< setw(15) << left << i << setprecision(15) << setw(20) << left << k << setw(20) << left << lfloat.at(i) << setw(20) << left << ldouble.at(i) << endl; 
         
   }
   

   else if (i>=2){

   lfloat.at(i)=lfloat.at(i-2)-lfloat.at(i-1);    // recurrence relation
   ldouble.at(i)= ldouble.at(i-2)-ldouble.at(i-1);
   
  cout<< setw(15) << left << i << setprecision(15) << setw(20) << left << k << setw(27) << left << lfloat.at(i) << left << ldouble.at(i) << endl;
 silver<< setw(15) << left << i << setprecision(15) << setw(20) << left << k << setw(20) << left << lfloat.at(i) << setw(20) << left << ldouble.at(i) << endl; 
         
   }
 
 
 }
 
silver.close();
cout<< "The data has been written to 'silver.txt'" << endl;
return 0;

}

bump
The problem is that you're declaring lfloat and ldouble inside the loop. That means that each iteration creates new lfloat and ldouble variables. As a result, when you compute the new values at lines 41 and 42, float.at(i-1) is zero.

Just move lines 21 and 22 above line 18

BTW, you don't need to write the data to cout and silver.txt. Just write it to cout. When the program is running correctly, enter "prog > silver.txt" to send cout to silver.txt. Be sure to remove line 53 since it won't be needed.
Thanks alot, that solved the problem.
Topic archived. No new replies allowed.