此代码将打印所需的完美数字(此处为4)。这是我的旧代码,会检查每个数字是否完美。它可以正常运行,并在6秒钟内完成,但是如果我在检查每个数字之前输入cls,它将受到很大的打击(大约100秒)。请告诉我背后的理论(为什么多个分类会影响性能)。
没有标准答案,例如“ Dude显然受到了打击,每次都在刷新屏幕。”
PS-我知道更好的方法不是检查完美数字而是生成它们。(根据Euclid-Euler定理)
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;
}
答案 0 :(得分:0)
运行system(“ cls”)时,您将创建一个新进程,并且每次选择新编号进行检查时都将执行此操作。 创建流程是一项昂贵的操作,更重要的是,如果您想要的只是更新屏幕上的当前编号,则不需要它。 足够写
cout << "The number under inspection: " << number << "\r";
cout.flush();
第一行将输出文本,并将光标返回到同一行的开头。 第二行将确保上述所有内容确实出现在显示屏上。 注意:这也是缓慢的操作,因此您可能需要对其进行速率限制。 我建议您每1000个左右输出1个数字。
答案 1 :(得分:0)
Windows CreateProcess()非常昂贵,比Unix fork()要昂贵得多。此外,system(“ cls”)是一种效率低下,不可移植的hack。您不能在非Windows系统中使用它。您可以使用支持控制台操作的ncurses库。
对于Windows,通过控制台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);
}