about for loop

+2 Zhifang Hu · January 5, 2016
Hi there

I am trying to write a nested for loop, however, it's not working as what i want. Here are the codes i've written

     ofstream results;
     results.open("results.txt");
     vector<double> signal;
     for(int t=0;t<1000;t++){
     for(int i=0; i<frequency.size();i++){
     double temp;
     temp+=amplitude*sin(2*pi*frequency/180*t+phase);
     signal.push_back(temp);
       results<<signal<<endl;
    }
     }


I tried to write out a txt file with the value of 'signal' i want and it should be the size of 1000 X 1.
What i intend to do is that
for the inner loop, there is a temp value for each "i" and they will be summed up for the inner loop. The results will keep as the first element of 'signal'. 
The outer loop repeats the inner loop 1000 times, hence i will get a 1000X1 vector, however, what i actually get is a much larger vector, which records every single value of the loop. Anyone have any suggestions?

Post a Reply

Replies

Oldest  Newest  Rating
0 Zhifang Hu · January 8, 2016
Thanks for the reply.

I realised that problem and put signal.push_back(temp)  in the outer loop.

BTW, i add a initialiser 

temp=0 in the start of outer loop, i am not sure if thats necessary.
  • 1

C++

107,227 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator