In my C++ code If I print sum outside loop it gives correct answer, but not in any loop for/while, why not? -
int main() { long long int first=0,second=1,t,n; //here t number of cases cin>>t; long long int fab=first+second; long long int sum[t]; for(long long int i=0;i<t;i++) { cin>>n; while(fab<n) { first=second; second=fab; if(fab%2==0) { sum[i]+=fab; } fab=first+second; } } for(int i=0;i<t;i++) { cout<<sum[i]<<endl; } return 0; }
in above loop sum not providing correct answer if sum used outside loop gives appropriate answer.
this:
cin >> t; long long int sum[t];
is not valid c++. array in c++ must created using compile-time expression denote number of items, not variable such t
.
the proper construct use standard c++ std::vector<long long>
:
#include <vector> //... cin >> t; std::vector<long long> sum(t);
the code standard c++.
the other aspect code solve issue brought in answer dietrichepp, in failed initialize vla 0. vector above have automatically initialized items 0 you.
so moral of story if used standard c++, not have had problem code.
Comments
Post a Comment