【问题标题】:Problems to validate a for cycle in C ++在 C++ 中验证 for 循环的问题
【发布时间】:2019-11-02 23:25:06
【问题描述】:

我做了这个程序,开始打印一个小矩形,然后打印其他更大的矩形,直到达到某个点,但假设当第一个循环结束时,程序的最后一个 for 必须做相反的事情,打印一个更大的矩形,然后打印更小的矩形,问题是程序只做第一个,忽略第二个,我不知道我是否错过了添加一些东西,有谁知道我会有什么错误?对不起,我还是个编程新手。

#include <iostream>                                                       
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>  
#include <windows.h> 
#include <time.h>

using namespace std;

void pos(int x,int y){  
      HANDLE hcon;  
      hcon = GetStdHandle(STD_OUTPUT_HANDLE);  
      COORD dwPos;  
      dwPos.X = x;  
      dwPos.Y= y;  
      SetConsoleCursorPosition(hcon,dwPos);  
}  

void square(int col1, int col2, int row1, int row2) //The square function is the one I use to print all the squares, just by changing the positions
{
    pos(col1,row1);
    cout << char(201);
    pos(col1,row2);
    cout << char(200);
    pos(col2,row1);
    cout << char(187);
    pos(col2,row2);
    cout << char(188);  

    for (int x = col1 + 1; x < col2; x++)
    {
        pos(x, row1);
        cout << char(205);

        pos(x, row2);
        cout << char(205);
    }
    for (int y = row1 + 1; y < row2; y++)
    {
        pos(col1,y);
        cout << char(186);

        pos(col2,y);
        cout << char(186);
    }
}

int main(){
    system("color 2E");

    int N = 22, N2 = 23;
    int x1 = 32, x2 = 33, y1 = 100, y2 = 105;
    int x3 = 4, x4 = 49, y3 = 4, y4 = 215;

    pos(30,30);
    cout << "Put the program in full screen so it can be better appreciated";
    Sleep(4000);
    system("cls");

    for (int i; i < N; i++){ //This for is responsible for printing the squares from minor to major

        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_BLUE | BACKGROUND_GREEN);

        Sleep(200);
        square (y1, y2, x1, x2);

        y1 = y1 - 5;
        y2 = y2 + 5;
        x1 = x1 - 1;
        x2 = x2 + 1;

        cout << "\n\n\n";
    }

    system("cls");

    for (int j; j < N2; j++){ //When the screen is clean, this for would have to start printing squares from major to minor

        SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_BLUE | BACKGROUND_GREEN);

        Sleep(200);
        square (y3, y4, x3, x4);

        y3 = y3 + 4;
        y4 = y4 - 4;
        x3 = x3 + 1;
        x4 = x4 - 1;

        cout << "\n\n\n";

        system("cls");
    }

    system("pause");
    return 0;
}

【问题讨论】:

  • 你的程序有未定义的行为,因为你没有初始化你的 for 循环索引变量。

标签: c++ windows winapi


【解决方案1】:

前面的评论是正确的。只是想知道为什么在编译程序时没有看到错误?您可能还想在第二个 for 循环结束时删除 system("cls") 以获得更好的视觉体验。

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2011-07-04
    • 1970-01-01
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多