c/c++代码 No.15 用一个字节控制8个家电的开和关

来源:互联网 发布:长安大学人工智能 编辑:程序博客网 时间:2024/04/28 07:00
#include <iostream>#include <iomanip>#include <windows.h>#include <conio.h>using namespace std;const char items[8][20] = {"冰箱", "电视", "电脑", "空调", "暖壶", "台灯", "闹钟", "门帘"};void gotoXY(int x, int y) {   COORD coord = {x, y};   SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);}void hideTheCursor() {   CONSOLE_CURSOR_INFO cciCursor;   HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);   if(GetConsoleCursorInfo(hStdOut, &cciCursor))   {      cciCursor.bVisible = FALSE;      SetConsoleCursorInfo(hStdOut, &cciCursor);   }}char* getBit(char n, char *str) {    int size = 8 * sizeof(char);    for (int i = size - 1; i >= 0; n >>= 1) {        str[i--] = (n & 1) + '0';    }    str[size] = '\0';    return str;}int toBit(char *str) {    int n = 0;    for (int i = 0; str[i] != '\0'; i++) {        n <<= 1;        n += str[i] - '0';    }    return n;}bool getBitW(char n, int w) {    int bitval = 1;    while (w--) {        bitval <<= 1;    }    return n & bitval;}int setBitW(char n, int w) {    int bitval = 1;    while (w--) {        bitval <<= 1;    }    return n ^ bitval;}int main(void) {    char status = 0;    char *str = new char[101];    int m[8] = {0};    hideTheCursor();    system("cls");    str = getBit(status, str);    cout << setfill('0') << setw(8 * sizeof(char)) << str << endl;    for (int i = 0; i < 8; i++) {        cout << items[i] << ':';        if (getBitW(status, i)) {            cout << "开启";            for (int j = 0; j < m[i]; j++) {                cout << '.';            }            m[i]++;            m[i] &= 7;        } else {            cout << "关闭";        }        cout << endl;    }    while (true) {        if (kbhit()) {            int a = getch() - '0';            if (a >= 1 && a <= 8) {                status = setBitW(status, a - 1);            }        }        gotoXY(0,0);        str = getBit(status, str);        cout << setfill('0') << setw(8 * sizeof(char)) << str << endl;        for (int i = 0; i < 8; i++) {            if (getBitW(status, i)) {                gotoXY(6,i + 1);                cout << "开启";                for (int j = 0; j < 8; j++) {                    if (m[i] > j) {                        cout << '.';                    } else {                        cout << ' ';                    }                }                m[i]++;                m[i] &= 7;            } else {                gotoXY(6,i + 1);                cout << "关闭";                for (int j = 0; j < 8; j++) {                    cout << ' ';                }            }        }        Sleep(50);    }    return 0;}
0 0
原创粉丝点击