此代码打印所需的no(4 here)完美数字。这是我的旧代码,检查每个数字是否完美。它运行正常并在6秒内完成,但是如果我在检查每个数字之前放置一个cls,它会受到很大的打击(大约100秒)。请告诉我背后的理论(为什么多重cls会影响性能)。
没有normie的答案就像“Dude显然需要点击,每次都刷新屏幕。”
PS-我知道更好的方法不是检查完美数字而是生成它们。(欧几里德 - 欧拉定理)
IDE-DevC ++
#include <iostream>
#include <string>
using namespace std;
int choice, quan, i, a[50], number;
string schoice;
void startgame()
{
choice = 3;
quan = 4;
system("cls");
cout << "Hey guys, today we are gonna print different types of numbers\n";
cout << "\nFollowing are some of the special numbers found in the known observable little universe of ours:- \n";
cout << "\n1. Prime numbers\n2. Square numbers\n3. Perfect Numbers\n\n";
cout << "Which ones do you wanna see?\n";
//cin >> choice;
cout << "\nCool! How many of them do you wanna see?\n";
//cin >> quan;
}
void perfect()
{
if (choice == 3)
{
int j = 0, y = 0, f = 0, number = 2;
do
{
//This is the cls in question
//system("cls");
cout << "The number under inspection: " << number << "\n";
f = 0;
for (i = (number - 1); i >= 1; i--)
{
if (number % i == 0)
{
f = f + i;
}
}
if (f == number)
{
//cout<<number<<", ";
a[j] = number;
j = j + 1;
y = y + 1;
}
number++;
}
while (y < quan);
system("cls");
cout << "\nHere are your " << quan << " perfect numbers starting from 1:-\n";
j = 1;
for (i = 0; i < quan; i++)
{
cout << a[i];
if (j != quan)
{
cout << ", ";
}
j++;
}
}
}
int main()
{
do
{
startgame();
perfect();
cout << "\n\nReturn to Main menu?(Y/N)\n";
schoice = "N";
//cin >> schoice;
}
while (schoice == "Y");
return 0;
}
当您运行system(“cls”)时,您将创建一个新进程,并且每次选择一个新数字进行检查时都会这样做。创建一个进程是一项昂贵的操作,更重要的是你不需要它,如果你想要的只是更新屏幕上的当前数字。写作就足够了
cout << "The number under inspection: " << number << "\r";
cout.flush();
第一行将输出文本并将光标返回到同一行的开头。第二行将确保显示所有上述内容。注意:这也是运行缓慢,因此您可能希望对其进行速率限制。我建议你输出1000左右的每1个数字。
Windows CreateProcess()相当昂贵,比Unix fork()贵得多。而且,系统(“cls”)是一种低效,不可移植的黑客。您不能在非Windows系统中使用它。您可以使用支持控制台操作的ncurses库。
对于Windows,通过Console API:
void clear() {
COORD topLeft = { 0, 0 };
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO screen;
DWORD written;
GetConsoleScreenBufferInfo(console, &screen);
FillConsoleOutputCharacterA(
console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
FillConsoleOutputAttribute(
console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE,
screen.dwSize.X * screen.dwSize.Y, topLeft, &written
);
SetConsoleCursorPosition(console, topLeft);
}