Condition issue with for loop
Apr 26, 2015 at 3:53pm UTC
Hi
I am a c++ beginer. I was testing some loops, when this problem occurred.
The code works perfectly fine while a<3
When a>=3 the two inner loop executes 1 more time, but it shouldnt.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
cin>>a
for (int n=0 ; n<a; ++n)
{
for (int sor=0; sor< pow(3,(n+1)); sor++)
{
for (int oszlop =0; oszlop<pow(3,(n+1)); oszlop++)
{
cout<<oszlop<< "/" << pow(3,(n+1))<<" " ;
}
cout << endl;
}
}
So i tested out like this:
1 2 3 4 5 6 7 8 9 10 11 12
cin>>a
for (int n=0 ; n<a; ++n)
{ q=pow(3,(n+1));
for (int sor=0; sor< q; sor++)
{
w=pow(3,(n+1));
for (int oszlop =0; oszlop<w; oszlop++)
{
cout<<oszlop<< "/" << pow(3,(n+1))<<" " ;
}
cout << endl; }
}
And worked perfectly.
The question is: What was the problem with the firs solution?
Last edited on Apr 26, 2015 at 3:53pm UTC
Apr 26, 2015 at 8:31pm UTC
It works fine for me. I just replaced 3 with 3.0. I wondering if it's a compiler problem. By the way, you should compute that value only once
1 2 3 4 5 6 7 8 9 10 11 12 13 14
cin>>a
for (int n=0 ; n<a; ++n)
{
p=pow(3.0,n+1);
for (int sor=0; sor< p; sor++)
{
for (int oszlop =0; oszlop<p; oszlop++)
{
cout<<oszlop<< "/" << p<<" " ;
}
cout << endl;
}
}
Topic archived. No new replies allowed.