2011-11-28 108 views
1
#include <iostream> 
#include <windows.h> 
using namespace std; 


int go_to(int x, int y) 
{ 
    COORD c; 
    c.X = x - 1; 
    c.Y = y - 1; 

    return SetConsoleCursorPosition (GetStdHandle(STD_OUTPUT_HANDLE), c); 
} 

void main(){ 
    int a=1; 

    while(a<10){ 
    a++; 
    cout<<"work"<<endl; 
    go_to(3,6); 
    cout<<"work"<<endl; 
    } 
} 

我不明白为什么这个循环只工作一次,也许你知道哪里是问题? 我遇到的问题是Cord,但不知道类似的方法来使用CORD。为什么我的循环只执行一次?

+2

你到底想干什么?你使用完全相同的参数调用9次'go_to',所以它总是会进入相同的位置。 –

+1

好吧,这只是一个例子,但为什么循环只能工作1次? – Wizard

+1

你如何确定它只被调用一次? – GManNickG

回答

6

变量a仅由a++;行修改,该行将其值增加1,并且不传递到go_to(x,y),因此它不受该函数影响。

您的循环肯定会运行值为a = {1到9},每次调用go_to(3, 6),并且还会打印两次。如果你不这么想,我相信你错了。

2

你的循环在每次迭代中都做同样的事情,所以你根本无法分辨它运行了多少次(9次)。

2

变化

while(a<10){ 
    a++; 
    cout<<"work"<<endl; 
    go_to(3,6); 
    cout<<"work"<<endl; 
} 

while(a<10){ 
    a++; 
    cout<<"work"<<endl; 
    go_to(a,a*2); 
    cout<<"work"<<endl; 
} 

,你会看到,它的实际运行多次。

0

这些值从未改变。

while(a<10){ 
    a++; 
    cout<<"work"<<endl; 
    go_to(3,6); 
    cout<<"work"<<endl; 
    } 

取而代之的是,尝试这样的事情:

for(int a = 0; a < 10; a++{ 
     cout<<"work"<<endl; 
     go_to(a + 3,a + 6); 
     cout<<"work"<<endl; 
     } 

这样你的价值将真正改变